1)对于==,若是做用于基本数据类型的变量,则直接比较其存储的 “值”是否相等;bash
若是做用于引用类型的变量,则比较的是所指向的对象的地址ui
2)对于equals方法,注意:equals方法不能做用于基本数据类型的变量this
若是没有对equals方法进行重写,则比较的是引用类型的变量所指向的对象的地址;spa
诸如String、Date等类对equals方法进行了重写的话,比较的是所指向的对象的内容。code
Object中的equals():对象
public boolean equals(Object obj) {
return (this == obj);
}
复制代码
String中的equals():hash
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String) anObject;
int n = length();
if (n == anotherString.length()) {
int i = 0;
while (n-- != 0) {
if (charAt(i) != anotherString.charAt(i))
return false;
i++;
}
return true;
}
}
return false;
}
复制代码
String中的hashCode():it
public int hashCode() {
int h = hash;
final int len = length();
if (h == 0 && len > 0) {
for (int i = 0; i < len; i++) {
h = 31 * h + charAt(i);
}
hash = h;
}
return h;
}
复制代码