To understand the above answer, you must first understand the difference between equals and = and the basic method of Integer

== == 1

  1. Basic types: byte, short, int, long, float, double, char, Boolean () in the 8 types exist stack
  2. Reference type: All that remains is reference type (the actual value of this type is stored in the heap, and the reference value of this value is stored in the stack)
  3. == : is the value in the stack being compared, which means that the real value is being compared for primitive types, and the reference value is being compared for reference types
  4. Equals: equals is not overridden (which is essentially also ==) and equals is overridden (e.g. Integer,String, etc.) to compare real values rather than references

2. The Integer explanation

Take a look at the following code and the result:

public static void main(String[] args) {
    Integer i1 = 127;
    Integer i2 = 127;
    Integer i3 = 128;
    Integer i4 = 128;
    System.out.println(i1 == i2); //true
    System.out.println(i1.equals(i2)); //true
    System.out.println(i3 == i4); //false
    System.out.println(i3.equals(i4)); //true
}
Copy the code

I3 and i4 use == to compare false, so why does this happen? Let’s keep digging!

When i3 == i4 is compared, the JDK does automatic boxing, which calls the following method:

public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); } IntegerCache: 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]; 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; Return new Integer(I);} private IntegerCache() {} return new Integer(I); == == == == == == == == public boolean equals(Object obj) { if (obj instanceof Integer) { return value == ((Integer)obj).intValue(); } return false; } {equals (128) == int(128);}} {equals (128) == int(128);Copy the code

It should also be clear from the above code why Integer should not be used ==, and you should use equals to compare all but the basic types in your code.