Method for judging Integer type value equality in Java
- 2021-08-12 02:50:52
- OfStack
Background
I encountered a very low-level problem in the development this week. Integer wrapper class equality judgment, The difference between wrapper classes and basic data types, Should be most people in the interview often asked, but sometimes everyone will be annoyed with these seemingly useless things, before the interview also need to be familiar with, bloggers before also think so, but usually look at some theoretical things, in the program discussion or feasibility analysis is very necessary, not much nonsense, look at this problem
Accident scene
public static void main(String[] args) {
Integer a =127;
Integer b = 127;
Integer c = 128;
Integer d = 128;
Integer e = 129;
Integer f = 129;
System.out.println(a==b); //true
System.out.println(c==d);//false
System.out.println(e==f);//false
System.out.println(a.equals(b));//true
System.out.println(c.equals(d));//true
System.out.println(e.equals(f));//true
}
Analyze the cause
In the above example, it can be seen that the comparison of 127 is OK, but 128 and 129 are not. In this case, see how Integer handles it.
Open the Integer class global search for the number 127 under 1. Why search for this 127, because 127 is ok, but 128 is not. Integer must have made special treatment for 127. After searching for 1, it was found that this number is concentrated in an internal class called IntegerCache. The code is as follows:
/**
* 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];
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;
}
private IntegerCache() {}
}
Look at the description of this inner class translated as:
Cached to support initialization of auto-boxed objects with values in the range of-128 to 127 (inclusive) as required by the java semantic specification
The cache is initialized on the first use, and the size of the cache is determined by the option {@ code-XX: AutoBoxCacheMax = < size > The java. lang. Integer. IntegerCache. high parameters are either copied and stored in private system variables of the sun. misc. VM class during virtual machine initialization
Generally speaking, in the range of-128 to 127, Integer does not create objects, but directly takes variable data from the system cache.
Solve
It is best to use equals for all wrapper classes. The equals method of Integer is as follows:
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
After judging the type, change it into int value to judge the size and return the result
Reflection
Although some theories are not very available at ordinary times, if the understanding of the theories is not in place and there is a misunderstanding, it is difficult to find out the problems arising in this case.