본문 바로가기

Programinng/Java

자바(Java) - Integer에서 -128~127이 == 동일(HashCode) 비교가 true인 경우

다음을 테스트 해보자

 

Integer a = -128
Integer b = -128
System.out.println(a == b); 

Integer c = 127
Integer d = 127
System.out.println(c == d); 

Integer e = new Integer(-127); 
Integer f = new Integer(-127); 
System.out.println(e == f); 

Integer g = new Integer(128); 
Integer h = new Integer(128); 
System.out.println(g == h);

 

 

- 결과

true

true

false

false

 

 

new라는 키워드를 사용하지 않고 -128~127은 헤쉬코드 비교를 했을때 true가 나온다.

그 이유는 저 코드를 역 컴파일 해보면 new를 사용하지 않은곳에 Integer a = Itneger.valueOf(-128);로 재정의 되어 있는 것을 확인 할 수 있다. 이는 Integer객체 안에 -128~127까지의 cache되어 미리 메로리에 올라와 있는 데이터를 가져다 쓰는 것인데 이렇게 하는 이유는 속도를 올리기 위해서이다. 하지만 자칫 잘못 사용했다가는 프로그램이 의도치 않게 동작할 수 있으므로 유의해야 한다.

 

Integer까보면 아래처럼 -128부터 127까지 cache처리 하는 코드를 확인해 볼 수 있다.

 

    private static class IntegerCache { 
        static final int high; 
        static final Integer cache[]; 

        static { 
            final int low = -128

            // high value may be configured by property 
            int h = 127
            if (integerCacheHighPropValue != null) { 
                // Use Long.decode here to avoid invoking methods that 
                // require Integer's autoboxing cache to be initialized 
                int i = Long.decode(integerCacheHighPropValue).intValue(); 
                i = Math.max(i, 127); 
                // Maximum array size is Integer.MAX_VALUE 
                h = Math.min(i, Integer.MAX_VALUE - -low); 
            } 
            high = h; 

            cache = new Integer[(high - low) + 1]; 
            int j = low; 
            for(int k = 0; k < cache.length; k++) 
                cache[k] = new Integer(j++); 
        } 

        private IntegerCache() {} 
    }