java

java Mutable value

kimbs0301 2024. 7. 4. 14:25

java의 Map 자료형 에서 정수값을 가져와 연산을 할 경우 jvm에 많은 Integer 객체가 생성될 수 있다.

 

Map<Integer, Integer> map = new HashMap<>();
...
// plus
map.put(1, map.get(1) + 10);
map.put(1, map.get(1) + 20);

 

Mutable Number 클래스를 만들어 많은 정수 객체가 만들어지는걸 방지할 수 있다.

public final class MutableInt {
    private int value;

    public MutableInt() {

    }

    public MutableInt(int value) {
        this.value = value;
    }

    public void increment() {
        value++;
    }

    public void decrement() {
        value--;
    }

    public void plus(int operand) {
        value += operand;
    }

    public void subtract(int operand) {
        value -= operand;
    }

    public int get() {
        return value;
    }

    @Override
    public String toString() {
        return Integer.toString(value);
    }
}

 

public final class IntHashMap<K> extends java.util.HashMap<K, MutableInt> {

    public IntHashMap() {

    }

    public IntHashMap(int capacity) {
        super(capacity);
    }

    public void plus(K key, int operand) {
        MutableInt mutableInt = super.get(key);
        if (mutableInt == null) {
            throw new RuntimeException("MutableInt is null " + key);
        }
        mutableInt.plus(operand);
    }

    public void subtract(K key, int operand) {
        MutableInt mutableInt = super.get(key);
        if (mutableInt == null) {
            throw new RuntimeException("MutableInt is null " + key);
        }
        mutableInt.subtract(operand);
    }

    public int getInt(K key) {
        MutableInt mutableInt = super.get(key);
        if (mutableInt == null) {
            throw new RuntimeException("MutableInt is null " + key);
        }
        return mutableInt.get();
    }
}

 

IntHashMap<Integer> map = new IntHashMap<>(300);
map.put(1, new MutableInt(0));

map.plus(1, 10);
map.plus(1, 20);

System.out.println(map.getInt(1));

 

operand(연산이 되는 수치값)에 값을 넘기면 멤버 변수값만 변동이 되므로 Integer 클래스를 사용한 것과 달리 새로운 객체가 생성되지 않는다.