一直认为的是:equals代表内容一致,而==表示地址一致。后来发现这个理解不太全面。
equals v.s. ==
equals的本质是==,但是在String、Integer等重写了equals方法。重写为值的比较,所以就有了上面那句话的理解。具体怎么重写的见源码(String类里的):
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
可以看到,重写后的equals方法包含‘==’。
情况一:地址一致则内容一致;
情况二:地址不一样,但内容一不一样未知,于是通过先比较字符长度再逐位比较的方法来比较值。
hashCode v.s. equals
equals相等,hashCode()必相等。反之,hashCode()相等,equals可能不相等。
下面是一些例子:
String a = "hel";
String b = "lo";
String c = "hello";
String d = "hello";
String e = new String("hello");
System.out.println(c == d); //true
System.out.println(c.equals(d)); //true
System.out.println(c.hashCode() == d.hashCode()); //true
System.out.println(c == e); //false
System.out.println(c.equals(e)); //true
System.out.println(c.hashCode() == e.hashCode()); //true
System.out.println(c == a+b); //false
System.out.println("hello" == a+b); //false
System.out.println("hello" == a+"lo"); //false
若有理解错误,请大佬指出,谢谢!