示例代码:
class User { private String name; public User(String name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return com.google.common.base.Objects.equal(getName(), user.getName()); } public String getName() { return name; } public void setName(String name) { this.name = name; } public static void main(String[] args) { List<User> us = new ArrayList<>(); while (true) { User u1 = new User("daxin"); User u2 = new User("daxin"); if(u1.hashCode()!=u2.hashCode()){ System.out.println(u1.equals(u2)); System.out.println(); } } } }
你会发现,纵然equals相等但是hashCode却不相等,在Map中这样的话会存在存储重复,即相同key对应多个value,因此必须重写hashCode方法保证equals相等则hashCode一定相等。