자바 갱 점 의 자동 분해 및 포장

1498 단어 자바
public static void main(String[] args) {
    Integer a = 1000;
    Integer b = 1000;
    Integer c = 100;
    Integer d = 100;
    System.out.println("a == b is" + (a == b));
    System.out.println("c == d is" + (c == d));
}

출력 결과:
a == b is false
c == d is true

자바 의 자동 포장 으로 인해 a 와 b 라 는 두 인용 변 수 는 같은 메모리 주 소 를 가리 키 지 않 습 니 다.사용==비교 할 때 기본 값 은 두 개의 메모리 주소 가 같은 지 비교 하 는 것 이기 때문에 a 와 b 는==으로 false 로 비교 합 니 다.
그런데 왜 c 와 d 용==비교 한 결과 true 일 까?자바 5 에 서 는 인 터 거 작업 에 메모리 절약 과 성능 향상 을 위 한 새로운 기능 을 도입 했다.전체 대상 은 같은 대상 인용 을 통 해 캐 시 와 재 활용 을 실현 합 니 다.
다음은 자바 의 자바 util.Integer 부분 소스 코드 입 니 다.
static {
        int h = 127;
        String integerCacheHighPropValue =
            sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
            try {
                int i = parseInt(integerCacheHighPropValue);
                i = Math.max(i, 127);
                h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
            } catch( NumberFormatException nfe) {
            }
        }
        high = h;

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

        // range [-128, 127] 
        assert IntegerCache.high >= 127;
    }

정수 구간-128~127 에 적용.자동 포장 에 만 사용 되 며 구조 함수 로 대상 을 만 드 는 것 은 적합 하지 않 습 니 다.

좋은 웹페이지 즐겨찾기