为什么重写 equals 方法 必须重写 hashCode

  自己学到这,就记录了下来,代码都是自己敲得,有不对的地方希望大神指点出来
为什么重写 equals 方法 必须重写 hashCode
  如果你重写了equals,比如说是基于对象的内容实现的,而不重写 HashCode,那么很可能某两个对象明明是“相等”,而hashCode却不一样.那么就会返回 false。例如在 HashSet 集合中,不允许存在相同元素,但是当你 new 两个对象,对象内容相同时,在 HashSet 集合中就存在了相同的两个元素,如何解决这个问题?那就要重写 equals 方法,但是重写 equals 方法还不能解决问题,因为在 HashSet 中判断两个元素是否相等是首先判断 hashCode 内存地址是否相等,如果不等在用 equals 方法判断内容是否相等,由于 new 了两个对象,虽然内容相同,但是在内存中开辟两两块地址,hashCode 肯定不同,所以还要重写 hashCode 方法。
 
下面是代码说明
public class Person {
//随便定义个类
  private int id;
  private String name;
  private int age;
  //set get 方法
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
   public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  //构造方法
  public Person(int id,String name, int age) {
    this.id=id;
    this.name = name;
    this.age = age;
  }
  //重写 hashCode 方法
  public int hashCode() {
    return this.getId();
  }
  //重写 equals 方法
  public boolean equals(Object obj) {
    if(this==obj){
      return true;
    }
    if(obj instanceof Person){
      if(this.getId()==((Person) obj).getId()){
        return true;
      }
    }
    return false;
  }
}
 
  测试类中代码
  //实例化
  Person p1 = new Person(1,"张三",12);
  Person p2 = new Person(1,"张三",12);
  // 声明 HashSet 集合类
  HashSet<Person> h = new HashSet<Person>();
  //添加数据
  h.add(p1);
  h.add(p2);
  //遍历集合
  for(Person per :h){
    System.out.println(per.getName());
  }
 
不重写 equals 和 hashCode 方法的执行结果
只重写 equals 方法的执行结果
重写 equals 和 hashCode 方法的执行结果
 
posted @ 2016-08-22 16:44  孤独的人生  阅读(250)  评论(0编辑  收藏  举报