请同时参考文章https://www.joshua317.com/article/200
代码语言:javascript复制package com.joshua317;
public class Main {
public static void main(String[] args) {
Integer i1 = new Integer(127);
Integer i2 = new Integer(127);
//两个引用对象,永远是不相等的,因为new生成的是两个对象,其内存地址不同
System.out.println("i1==i2:" (i1 == i2));//false
Integer i3 = new Integer(128);
Integer i4 = new Integer(128);
//两个引用对象,永远是不相等的,因为new生成的是两个对象,其内存地址不同
System.out.println("i3==i4:" (i3 == i4));//false
Integer i5 = 127;//自动装箱,底层是Integer.valueOf()
Integer i6 = 127;//自动装箱,底层是Integer.valueOf()
//-128~127走值缓存,同一个对象引用
System.out.println("i5==i6:" (i5 == i6));//true
Integer i7 = 128;//自动装箱,底层是Integer.valueOf()
Integer i8 = 128;//自动装箱,底层是Integer.valueOf()
//-128~127走值缓存,超出范围,产生不同对象
System.out.println("i7==i8:" (i7 == i8));//false
Integer i9 = 127;//自动装箱,底层是Integer.valueOf()
Integer i10 = new Integer(127);
//不同对象引用
System.out.println("i9==i10:" (i9 == i10));//false
Integer i11 = 128;//自动装箱,底层是Integer.valueOf()
Integer i12 = new Integer(128);
//不同对象引用
System.out.println("i11==i12:" (i11 == i12));//false
Integer i13 = 127;//自动装箱,底层是Integer.valueOf()
Integer i14 = Integer.valueOf(127);
//-128~127走值缓存,同一个对象引用
System.out.println("i13==i14:" (i13 == i14));//true
Integer i15 = 128;
Integer i16 = Integer.valueOf(128);
//-128~127走值缓存,超出范围,产生不同对象
System.out.println("i15==i16:" (i15 == i16));//false
Integer i17 = Integer.valueOf(127);
Integer i18 = Integer.valueOf(127);
//-128~127走值缓存,同一个对象引用
System.out.println("i17==i18:" (i17 == i18));//true
Integer i19 = Integer.valueOf(128);
Integer i20 = Integer.valueOf(128);
//-128~127走值缓存,超出范围,产生不同对象
System.out.println("i19==i20:" (i19 == i20));//false
System.out.println("============华丽分割线============");
/**
* Integer变量和int变量比较时,只要两个变量的值是向等的,则结果为true
* 因为包装类Integer和基本数据类型int比较时,Java会自动拆包装为int,
* 然后进行比较,实际上就变为两个int变量的比较
*/
Integer i21 = 127;
int i22 = 127;
System.out.println("i21==i22:" (i21 == i22));//true
Integer i23 = 128;
int i24 = 128;
System.out.println("i23==i24:" (i23 == i24));//true
Integer i25 = new Integer(127);
int i26 = 127;
System.out.println("i25==i26:" (i25 == i26));//true
Integer i27 = new Integer(128);
int i28 = 128;
System.out.println("i27==i28:" (i27 == i28));//true
Integer i29 = Integer.valueOf(127);
int i30 = 127;
System.out.println("i29==i30:" (i29 == i30));//true
Integer i31 = Integer.valueOf(128);
int i32 = 128;
System.out.println("i31==i32:" (i31 == i32));//true
}
}