大家好,又见面了,我是全栈君。
/**
* @time 2014-06-25
* @author Cao HaiCheng
*
*/
public class demo {
public static void main(String[] args) {
test1();
test2();
test3();
test4();
test5();
}
/**
* 第一个答案是false非常好理解,由于'=='操作符比較的是两个对象的地址,a和b指向的地址不同
*/
private static void test1() {
Integer a = new Integer(50);
Integer b = 50;
System.out.println("test1执行结果:"+(a == b)); //false
}
/**
* 这个答案是true,Integer a=50属于自己主动装箱,调用的是编译器中的public static Integer valueOf(int i)方法
* 我们看下这种方法:
* public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
*
* 我们能够看到jdk源代码中定义的这种方法意思是这种:当i的值在某个范围之间的时候不用创建对象,直接去IntegerCache中取,再看下这个
* 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) {
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);
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
private IntegerCache() {}
}
* 我们看到这个Cache里面放了256个值,就是-128到127之间的值
* 所以当Integer a = 50; 的时候并没有创建新的对象,还是引用的缓存池中的地址,所以这个结果为true
*/
private static void test2() {
Integer a = 50;
Integer b = 50;
System.out.println("test2执行结果:"+(a == b)); //true
}
/**
* 这个依据上面那个说法就简单了,由于150并不在-128到127之间,所以这个须要自己创建对象,创建的对象a和b的指向地址不同
* 所以该结果为false;
*/
private static void test3() {
Integer a = 150;
Integer b = 150;
System.out.println("test3执行结果:"+(a == b));//false
}
/**
* 这个 Integer a = Integer.valueOf(50); 和Integer b = 50; 调用的方法都是编译器中的public static Integer valueOf(int i)方法
* 所以两个50都没有创建新的对象,都是从缓存池中拿到的对象,所以结果为true
*/
private static void test4() {
Integer a = Integer.valueOf(50);
Integer b = 50;
System.out.println("test4执行结果:"+(a == b)); //true
}
/**
* 同理,数值超出了范围,所以指向不同,结果为false
*/
private static void test5() {
Integer a = Integer.valueOf(150);
Integer b = 150;
System.out.println("test5执行结果:"+(a == b)); //false
}
}
版权声明:本文博客原创文章,博客,未经同意,不得转载。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/117485.html原文链接:https://javaforall.cn