引用类型和基本类型的分类,不在写了,网上有很多。
我们知道:
当两个基本类型使用”==”比较时,他们比较的是值。
当两个引用类型使用”==”比较时,他们比较的是地址。
当两个引用类型使用方法equals()比较时,他们比较的是值。
但当基本类型和他的包装类(引用类型)使用”==”比较时,
他们的结果又是如何呢?
下面我们使用Integer和int进行说明。
Integer是int的包装类。 int 基本类型, Integer 为引用类型。
看个例子:
int i = 1234;
Integer i1 = new Integer(1234);
Integer i2 = new Integer(1234);
System.out.print("i1 == i2 : "+(i1 == i2));
System.out.println("\ti1.equals(i2) : "+(i1.equals(i2)));
System.out.print("i == i1 : "+(i == i1));
System.out.println("\t\ti1.equals(i) : "+(i1.equals(i)));
System.out.print("i == i2 : "+(i == i2));
System.out.println("\t\ti2.equals(i) : "+(i2.equals(i)));
打印:
i1 == i2 : false i1.equals(i2) : true
i == i1 : true i1.equals(i) : true
i == i2 : true i2.equals(i) : true
我们可以看到 i == i1, i == i2, i1 != i2,
但使用equals()他们都是相等的。
接着我们来看看jdk1.8中Integer类中的方法equals()
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
可以观察到使用equals(),他们比较的是值。
总结:当比较基本类型和他的包装类(引用类型)使用”==”和方法equals()比较时,他们比较的都是值。
Integer和其它基本类型都相同,大家有兴趣可以去证明,在此我都不在写了。