如有个User对象如下:
public class User {
private String name;
private Integer age;
}
如果不重写equals方法和hashcode方法,则:
public static void main(String[] args) {
User user1 = new User("userA", 30);
User user2 = new User("userB", 30);
System.out.println(user1.equals(user2)); // false
System.out.println(user1.hashCode() == user2.hashCode()); // false
System.out.println(user1.hashCode());
System.out.println(user2.hashCode());
}
equals:
@Override
public boolean equals(Object obj) {
if (null == obj) {
return false;
}
if (obj == this) {
return true;
}
if (!(obj instanceof User)) {
return false;
}
User anoUser = (User) obj;
if (Objects.equals(this.name, anoUser.name) && Objects.equals(this.age, anoUser.age)) {
return true;
}
return false;
}
hashcode:
@Override
public int hashCode() {
return Objects.hash(this.name, this.age);
}
// 或
@Override
public int hashCode() {
int result = 1;
if (this.name == null && this.age == null) {
return result;
}
result = 31 * result + (this.name == null ? 0 : this.name.hashCode());
result = 31 * result + (this.age == null ? 0 : this.age.hashCode());
return result;
}
如果hashcode返回一个固定值,则HashMap每次都要找同一个位置,导致链表很长,效率很低。