Integer的“==”
使用Integer时,我们可能会遇到以下令人困惑的现象`
public static void main(String[] args)
{
Integer a=11;
Integer b=11;
if(a==b)
System.out.println("true");
else
System.out.println("false");
}
输出结果为:true
但是,如果变为以下:
public static void main(String[] args)
{
Integer a=1111;
Integer b=1111;
if(a==b)
System.out.println("true");
else
System.out.println("false");
}
输出结果就变为了:false
这是神马情况??
其实,Integer与int不一样,它是一个类(对象包装器),而int是基本类型,不属于类。比较两个对象是否相当,需要使用equals方法。而“==”是检测两个对象是否指向同一个存储区域。因此比较a和b应该使用equals方法:
public static void main(String[] args)
{
Integer a=1111;
Integer b=1111;
if(a.equals(b))
System.out.println("true");
else
System.out.println("false");
}
结果为:true
那为什么第一次使用“==”比较,输出也为true呢?
那是因为,介于-127~128的int会被包装到固定的对象中,它们的存储区域是相同的,检测结果自然是“true”
Integer.valueOf(int) 方法,,也是同样的,会去固定的对象。下面i、j是相同的。
Integer i = Integer.valueOf(1);
Integer j = Integer.valueOf(1);
还有一种情况:
Integer a = new Integer(1);
Integer b = 1;
if(a == b){
System.out.println(true);
}else{
System.out.println(false);
}
结果是:
false
Process finished with exit code 0
new一定是创建新对象。