아래 코드를 한 번 살펴보자.
Integer c = Integer.valueOf(127);
Integer d = Integer.valueOf(127);
System.out.println("c.hashCode() = " + c.hashCode());
System.out.println("d.hashCode() = " + d.hashCode());
System.out.println("System.identityHashCode(c) = " + System.identityHashCode(c));
System.out.println("System.identityHashCode(d) = " + System.identityHashCode(d));
System.out.println("(c==d) = " + (c==d));
자바의 hashCode는 값을 기반으로 생성하기 때문에 c와 d의 hashCode는 같다.
하지만 identityHashCode는 객체 고유 HashCode로 둘은 달라야하고 c==d는 false가 출력돼야 할 것 같다.
그런데 identityHashCode가 같고 == 비교도 같다고 출력된다.
왜 이럴까?
Integer 클래스는 내부에 캐싱하는 전략을 수립하고 있다.
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer[] cache;
static Integer[] archivedCache;
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
h = Math.max(parseInt(integerCacheHighPropValue), 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
// Load IntegerCache.archivedCache from archive, if possible
CDS.initializeFromArchive(IntegerCache.class);
int size = (high - low) + 1;
// Use the archived cache if it exists and is large enough
if (archivedCache == null || size > archivedCache.length) {
Integer[] c = new Integer[size];
int j = low;
for(int i = 0; i < c.length; i++) {
c[i] = new Integer(j++);
}
archivedCache = c;
}
cache = archivedCache;
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
최소 -128부터 최대 127까지 캐싱하는 모습을 볼 수 있다.
그리고 valueOf 메서드를 살펴보면 내부에서 이 캐싱한 값을 이용해 Integer객체를 반환한다.
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
그럼 127을 넘어서는 값은 캐싱하지 않는지 직접 확인해보자.
Integer a = Integer.valueOf(128);
Integer b = Integer.valueOf(128);
System.out.println("a.hashCode() = " + a.hashCode());
System.out.println("b.hashCode() = " + b.hashCode());
System.out.println("System.identityHashCode(a) = " + System.identityHashCode(a));
System.out.println("System.identityHashCode(b) = " + System.identityHashCode(b));
System.out.println("(a==b) = " + (a==b));
위 코드의 결과는 아래와 같다.
identityHashCode도 다르고 == 비교도 false가 출력됐다.
Long 또한 캐싱하는 전략을 사용한다.
결론은 equals를 통해서 값을 비교하자... == 비교는 매우 위험한 비교다.
'Java' 카테고리의 다른 글
Record Class 도입기 (0) | 2024.05.03 |
---|---|
테스트 코드 그리고 리팩토링 (0) | 2024.04.19 |
[우아한 테크 세미나] 우아한 객체지향 - 1 (0) | 2024.04.08 |
[WAS를 만들어보자 (3)] HttpMessageBody 추출하기 (1) | 2024.03.23 |
[WAS를 만들어보자 (2)] HTTP 메세지 출력하기 (0) | 2024.03.23 |