
알고리즘 문제를 풀던 도중 Integer 타입임에도 불구하고 "=="로 값을 비교했다..
소스코드 리팩토링시 Integer는 객체인데 어떻게 "=="로 비교가 되지? 라는 의문이 이 글의 시작이다.
/*
* Cache to support the object identity semantics of autoboxing for values between
* -128 and 127 (inclusive) as required by JLS.
... 생략 ...
*/
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer[] cache;
...
중략
...
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
@IntrinsicCandidate
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
}
static final Integer[] cacheInteger타입 변수는 [-128,127] 범위까지는 캐싱이 되어있기에 ==로 비교가 가능하다.
하지만 값의 범위를 신경써야하니 객체면 equals를 사용하는것이 실수를 줄이는 방법일 것