一、直接使用==
public class EqualsMethod {
public static void main(String[] args) {
Integer n1 = new Integer(23);
Integer n2 = new Integer(23);
System.out.println(n1 == n2);
}
}
输出为:false
两个值相同,为啥会输出false呢?
尽管对象的内容相同,然而对象的引用却是不同的,而==和!=比较的是对象的引用,所以会输出false。
二、使用equals
如果想比较两个对象的实际内容是否相同,此时必须使用所有对象都适用的特殊方法equals(),但这个方法不适用于基本类型,基本类型直接使用==和!=即可。
public class EqualsMethod {
public static void main(String[] args) {
Integer n1 = new Integer(23);
Integer n2 = new Integer(23);
System.out.println(n1.equals(n2));
}
}
输出为:true
三、创建自己的类
如果自己创建一个类呢
class Value{
int i;
}
public class EqualsMethod {
public static void main(String[] args) {
Value v1 = new Value();
Value v2 = new Value();
v1.i = v2.i = 23;
System.out.println(v1.equals(v2));
}
}
输出为:false
结果又为false,这是由于equals()的默认是比较引用的,所以除非在自己的新类中覆盖equals()方法,否则会得到不是我们想要结果。
四、比较
equals()默认的比较引用,为什么第二种会得到正确的结果呢,是由于Integer这个类覆盖了equals()方法。下面是Integer类中equals()方法。
/**
* Compares this object to the specified object. The result is
* {@code true} if and only if the argument is not
* {@code null} and is an {@code Integer} object that
* contains the same {@code int} value as this object.
*
* @param obj the object to compare with.
* @return {@code true} if the objects are the same;
* {@code false} otherwise.
*/
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}