1、equals()
(1)“==”操作符比较两端的两个引用是否指向堆内存中同一块地址
(2)对象的内容相等需要符合两个条件:①对象的类型相同(可以使用instanceof操作符进行比较);②两个对象的成员变量的值完全相同;
(3)调用方法
boolean b = u1.equals(u2);
(4)equals的复写
public boolean equals(object obj) {
if (this == obj) {
return true;
}
boolean b = obj instanceof User;
if (b) {
User u = (User) obj;
if (this.age == u.age && this.name.equals(u.name)) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
2、hashCode()
存在于Object中,如果map中的键为类对象则需要复写该方法,复写方法如下。
// 可调用指定的hash算法
public int hashCode() {
int result = 17;
result = 31 * result + age;
result = 31 * result + name.hashCode();
return result;
}
3、toString()将对象转换为字符串,增加对象的可读性。复写方法如下:
public String toString() {
String result = "Age: " + age + ", Name: " + name;
return result;
}