[Java] Integer의 값 비교

이대건·2024년 2월 1일

Java

목록 보기
7/17
post-thumbnail

알고리즘 문제를 풀던 도중 Integer 타입임에도 불구하고 "=="로 값을 비교했다..
소스코드 리팩토링시 Integer는 객체인데 어떻게 "=="로 비교가 되지? 라는 의문이 이 글의 시작이다.

IntegerCache

  • Integer 값 비교 검색에서 IntegerCache라는 키워드를 알게되었다.
  • 공식문서에서는 찾을 수 없었으나 Integer.java에서 이너클래스로 선언된 IntegerCache와 주석을 확인할 수 있었다.
    Integer.java
/*
* 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);
    }   
}

==로 값을 비교할 수 있는 이유

  • IntegerCache 주석과 IntegerCache의 멤버변수를 확인하면 알 수 있다.
  • [-128,127] 범위의 수를 IntegerCache.cache 배열에 캐싱한다.
    static final Integer[] cache

캐싱하는 이유

  • valueOf의 주석을 확인하면 알 수 있다.
  • IntegerCache.valueOf를 보면 시공간적 성능 향상을 위해 자주 사용하는 값인 [-128. 127] 범위 값을 항상 캐싱한다고 한다.

정리

Integer타입 변수는 [-128,127] 범위까지는 캐싱이 되어있기에 ==로 비교가 가능하다.
하지만 값의 범위를 신경써야하니 객체면 equals사용하는것이 실수를 줄이는 방법일 것

결론

  • 객체비교에서는 항상 equals를 사용하자!
profile
일낸머스크

0개의 댓글