上期我们讲过自动拆箱自动装箱是JDK1.5之后的新特性
下面我们讲讲关于这里的一个“128陷阱”
public static void main(String[] args) {
Integer k=100;
//Integer是一个引用数据类型,又是一个对象
//100默认是一个基本数据类型
//我们相当于把基本数据类型赋值给一个对象
// 对象 = 基本数据类型
Integer m=100;
int i=100;
Integer j=new Integer(100);
System.out.println("k和m比较");
System.out.println(k==m);//ture
//ture,证明两个Integer同时指向了常量池中的100(缓存机制)
System.out.println("k和 i 比较");
System.out.println(k==i);//ture
//ture,证明Integer和int指向常量池的100
System.out.println("k和 j 比较");
System.out.println(k==j);//false
//false,证明new方法出来的integer对象在堆中,引用地址不同为false
Integer a = 127;
Integer b = 127;
Integer c = 128;
Integer d = 128;
System.out.println("a和b比较");
System.out.println(a == b);//ture
System.out.println("c和d ==比较");
System.out.println(c == d);//false
//证明只有-128~127(128陷阱)会加载到常量池中,其他会在堆中开辟不同空间
System.out.println("c和d .intValue()比较");
System.out.println(c.intValue() == d.intValue());//ture
//ture,证明也可以主动调用拆箱方法使得Integer的值可以比较
System.out.println("c和d equals比较");
System.out.println(c.equals(d));//ture
//true,证明integer重写了equals()方法,我们可以用来比较
}
我们先猜一下输出true还是false
这里可以看出在int的包装类Integer在127以及之前的时候是可以使用==去判断两个数是否相等的,而在Integer是128的时候就不能去判断这两个数是否相等。
这里涉及自动拆箱自动装箱
Integer k=100;//自动装箱机制
//相当于进行下面这一步
Integer k=Integer.valueOf(100);
这里我们好奇为什么c和d比较为什么返回false
如果要问他的原因,让我们读一下Integer的valueOf()源码
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
我们发现,IntegerCache.low和IntegerCache.high可以在上面代码定义中看到,定义的为-128和127,看代码可知,如果这个数 i 实在-128到127之间则直接返回这个已经定义在数组中的值,而不再这个范围中则需要去new一个新的对象,我们知道在java中==比较是储存对象的地址,在大于等于128的情况下他其实是new了两个对象
用 = =判断自然是不可取的,因为他是俩对象,结果返回自然是false,这里我们要判断应该是使用equals。