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 클래스를 사용한 것과 달리 새로운 객체가 생성되지 않는다.
'java' 카테고리의 다른 글
java windows 백그라운드 실행 및 종료 (0) | 2024.07.04 |
---|---|
java Map ConcurrentModificationException 회피 (0) | 2024.07.04 |
java 8byte guid 생성 (0) | 2024.07.04 |
java Virtual Thread Producer Consumer 패턴 (0) | 2024.07.04 |
java 정규식 문자열 추출 (0) | 2024.07.04 |