一、Java中的 ==
1、对于基本数据类型,比较的是其值
public class Test {
public static void main(String[] args) {
int a = 12043;
int b = 12043;
System.out.println(a == b);
}
}
运行结果为:true
2、对于对象的引用,比较的是对象的内存地址
public class Test {
public static void main(String[] args) {
Integer c = 19328;
Integer d = 19328;
System.out.println(c == d);
}
}
运行的结果为:false
二、Java中的 equals
对于Java中的 equals 方法,很多类都会重写 equals 方法,我们可以看源码来了解不同类的equals 方法,这里用 Integer 类中的 equals 方法来演示!
public class Test {
public static void main(String[] args) {
Integer c = 19328;
Integer d = 19328;
System.out.println(c.equals(d));
}
}
运行结果为:true
Integer 类所重写的 equals 源码
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
从源码中,我们可以看到,首先比较的是 是否是Integer类,再其次比较的是 值
所以对于equals方法,我们不应该一概而论,看源码时了解这个方法的最快方式~