Integer de Java por qué la comparación con == dirección de los resultados será diferente?


1. Problema

  • Entero por qué la comparación con == abordaría resultado diferente?
  • En el siguiente ejemplo, ¿por qué i1 == i2es falso, i3 == i4pero es cierto?
public class Test {
    public static void main(String[] args) {
        Integer i1 = 250;
        Integer i2 = 250;
        Integer i3 = 250;
        Integer i4 = 250;
        System.out.println(i1==i2);//false
        System.out.println(i1.equals(i2));//true
        System.out.println(i3==i4);//true
        System.out.println(i3.equals(i4));//true
    }
}

2. Las respuestas

  • existe clase Entero IntegerCache clase caché, un valor entero de caché predeterminado -128 y 127, en caso de que el rango de valores [-128,127] se puede convertir directamente desde el IntegerCache cuando Integer;
  • ¿Por qué hacer esto caché [-128,127] ella?
  • [-128,127] byte es el rango, en el IO arroyos, cada documento de lectura, la unidad básica es un byte 1, se puede utilizar IntegerCache objeto de clase caché no crea una gran cantidad de tiempo de envasado automático.;
  • referencia de API como sigue:
    /**
     * 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
     * jdk.internal.misc.VM class.
     *
     * WARNING: The cache is archived with CDS and reloaded from the shared
     * archive at runtime. The archived cache (Integer[]) and Integer objects
     * reside in the closed archive heap regions. Care should be taken when
     * changing the implementation and the cache array should not be assigned
     * with new Integer object(s) after initialization.
     */

    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer[] cache;
        static Integer[] archivedCache;

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    h = Math.max(parseInt(integerCacheHighPropValue), 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            // Load IntegerCache.archivedCache from archive, if possible
            VM.initializeFromArchive(IntegerCache.class);
            int size = (high - low) + 1;

            // Use the archived cache if it exists and is large enough
            if (archivedCache == null || size > archivedCache.length) {
                Integer[] c = new Integer[size];
                int j = low;
                for(int i = 0; i < c.length; i++) {
                    c[i] = new Integer(j++);
                }
                archivedCache = c;
            }
            cache = archivedCache;
            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }
        
        private IntegerCache() {}
    }
Publicados 201 artículos originales · ganado elogios 200 · Vistas 6360

Supongo que te gusta

Origin blog.csdn.net/Regino/article/details/104733858
Recomendado
Clasificación