JAVA 자동 권투와 언 박싱 및 정수 풀

포장의 형태에 대응 1. 기본 클래스

	byte->Byte;
    short->Short;
    int->Integer;
    long->Long;
    double->Double;
    float->Float;
    char->Charecter;
    boolean->Boolean;

자동 및 자동 포장 풀기

오토 박싱 : 기본 데이터 유형이됩니다 자동으로 해당 패키지로 변환.

언 박싱 자동 : 자동으로 해당 포장의 기본 데이터 유형으로 변환됩니다.

Integer i = new Integer(1);
Integer i = 1; //自动装箱

Integer j = 2; 
int k = j;//自动拆箱

자동 장면 입력 상자

  • 기본 유형과 크기 비교 포장 유형, 4 개 개의 조작, 조건 연산자
  • 컬렉션 클래스를 사용하는 경우에만 개체를 ​​받아, 그것을 오토 박싱 것

3. 예

public static void main(String[] args) {
        Integer i1 = new Integer(100);
        Integer j1 = new Integer(100);
        System.out.println(i1==j1);	//false

        Integer i2 = new Integer(100);
        int j2 = 100;
        System.out.println(i2==j2);	//true

        Integer i3 = new Integer(100);	//heap
        Integer j3 = 100;			//constant pool
        System.out.println(i3==j3);	//false

        Integer i4 = 127;
        Integer j4 = 127;
        System.out.println(i4==j4);	//true

        Integer i5 = 128;
        Integer j5 = 128;
        System.out.println(i5==j5); //false
    }

정수 풀 범위의 정수 상수 : 127 -128, 그래서 자동 포장의 INT 정수 시간에 반환 밖으로 127 -128의 당신 INT 값이 새 정수 객체가 아닌 그러나 그것은 정수 개체 힙에 캐시되었습니다.
소스 코드의 정수 유형 :

/**
     * Cache to support the object identity semantics of autoboxing for values between
     * -128 and 127 (inclusive) as required by JLS.
     *
     * The cache is initialized on first usage.  The size of the cache
     * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
     * 可以通过参数指定
     * During VM initialization, java.lang.Integer.IntegerCache.high property
     * may be set and saved in the private system properties in the
     * sun.misc.VM class.
     */

    private static class IntegerCache {
        static final int low = -128;//最小值
        static final int high;//最大值
        static final Integer cache[];//范围内的数组缓存

        static {//静态内部类,用于添加数组
            // high value may be configured by property
            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);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            cache = new Integer[(high - low) + 1];//实例化cache缓存
            int j = low;
            for(int k = 0; k < cache.length; k++)//进行赋值
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;//断言必须大于127
        }

        private IntegerCache() {}
    }

    /**
     * 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
     */
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];//引用地址相同
        return new Integer(i);
    }

내부 정적 IntegerCache.cache는 클래스가로드 된 정수의 일정한 배열을 달성 -128에서 127 사이의 정수 정적 객체 초기화를 수행하는 블록 정적 캐시 어레이에 저장된다. 캐시 자바 접근 영역에 저장되어있는 일정에 속하는.

4. 정수 풀

개체의 수를 감소 원시 래퍼 클래스가 구현하는 자바 상수 풀 기술의 대부분은 메모리 사용을 줄이고 성능을 향상시키기 위해 사용되는 만들었습니다. 이러한 바이트, 짧은, 정수, 롱, 문자, 부울로, 유형 플로트 래퍼 플로트 두 가지, 두 기술은 상수 풀을 달성하지 않았다.

출시 세 원저 · 원의 칭찬 0 · 조회수 75

추천

출처blog.csdn.net/InnIMerSyngur/article/details/104074116