2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Let's look at a piece of code first
int a0=127;
int a1=127;
Integer a2=127;
Integer a3=127;
System.out.println(a0==a1); // 1、运行结果是true
System.out.println(a0==a2); // 2、运行结果是true
System.out.println(a2==a3); // 3、运行结果是true
System.out.println(a2.equals(a0)); // 注意这里必须是包装类的a2才能使用equals,a0不能使用
// 4、运行结果是true
System.out.println(a2.equals(a3)); // 5、运行结果是true
System.out.println("-----------------------------");
int b0=200;
int b1=200;
Integer b2=200;
Integer b3=200;
System.out.println(b0==b1); // 6、运行结果是true
System.out.println(b0==b2); // 7、运行结果是true
System.out.println(b2==b3);// 8、运行结果是false
System.out.println(b2.equals(b0)); // 9、运行结果是true
System.out.println(b2.equals(b3)); // 10、运行结果是true
Is the running result the same as you expected?
In fact, the 8th running result is the so-called 128 trap.
The Java 128 trap means that when the value stored in the encapsulation class of the basic type data is greater than or equal to 128, the addresses of each class are not equal. It does not have to be 128 to appear
In simple terms, when the value is less than or equal to 127 and greater than or equal to -128, the value that is automatically boxed is the value at the same address. When the value is greater than 127, the value that is automatically boxed is not the same. That is, as long as the range is not [-128, 127], the result of using == is false. If equals is used, the result is true. Although the value is not in the current range, if Integer is used, it is automatically unboxed, so there will be no 128 trap problem, so the 7th operation is true;
/**解释精简一部分后
* This method will always cache values in the range -128 to 127
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
illustrate:
1. The value of IntegerCache.low is -128, and the value of IntegerCache.high is 127.
2. In the valueOf method of Integer, a cache array is stored. This array is equivalent to a cache, ranging from -128 to 127.
3. When the value we take is between [-128, 127], the value defined in the IntegerCache.cache array is returned, and there is no need to create a new object.
4. When the value is not in the range, a new object needs to be created. The new object == is the address to be judged, which is false; equals is the value of the object to be judged, which is true.
Integer k1 = new Integer(100);
Integer k2 = new Integer(100);
System.out.println(k1==k2); // 运行结果false
System.out.println(k1.equals(k2)); // 运行结果true
Reference Documents:
https://blog.csdn.net/niu_8865/article/details/110791911
https://blog.csdn.net/DianLanHong/article/details/119617352
https://blog.csdn.net/Yangyeon_/article/details/135611919