equals和hashcode的区别

     equals和hashcode是java.lang.Object类的两个重要的方法,hashCode()方法和equal()方法的作用其实一样,在java中都是用来对比两个对象是否相等一致,

 那么equal()既然已经能实现对比的功能了,为什么还要hashCode()呢?

       因为重写的equal()方法里需要比较的,比较全面比较复杂,这样效率就比较低,而利用hashCode()进行对比,则只要生成一个hash值进行比较就可以了,效率很高,

那么hashCode()既然效率这么高为什么还要equal()呢?

       因为hashCode()并不是完全可靠,有时候不同的对象他们生成的hashcode也会一样(与hashcode算法有关),所以hashCode()只能说是大部分时候可靠,并不是绝对可靠,所以我们可以得出:

         1.equal()相等的两个对象他们的hashCode()肯定相等,也就是用equal()对比是绝对可靠的。

         2.hashCode()相等的两个对象他们的equal()不一定相等,也就是hashCode()不是绝对可靠的。

  总的来说,Object类默认的equals比较规则就是比较两个对象的内存地址。而hashcode是本地方法,java的内存是安全的,因此无法根据散列码得到对象的内存地址,但实际上,hashcode是根据对象的内存地址经哈希算法得来的,所以无法保证两个对象的内存地址是否一致。

给HashSet中存放自定义类型元素时,需要重写对象中的hashCode和equals方法,建立自己的比较方式,才能保证HashSet集合中的对象唯一
如:
public class Student { 
  private String name; 
  private int age; 
  public Student() {
      
  }
  public Student(String name, int age) {
    this.name = name; 
    this.age = age; 
    }
    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; 
    }
    @Override
    public boolean equals(Object o) { 
    if (this == o) 
        return true; 
    if (o == null || getClass() != o.getClass()) 
        return false; 
    Student student = (Student) o; 
    return age == student.age && Objects.equals(name, student.name); 
    }
    @Override 
    public int hashCode() { 
    return Objects.hash(name, age); 
    } 
    }
    public class HashSetDemo2 { 
    public static void main(String[] args) { 
    //创建集合对象 该集合中存储 Student类型对象 HashSet<Student> stuSet = new HashSet<Student>(); 
    //存储 Student stu = new Student("于谦", 43); 
    stuSet.add(stu); 
    stuSet.add(new Student("郭德纲", 44)); 
    stuSet.add(new Student("于谦", 43)); 
    stuSet.add(new Student("郭麒麟", 23)); 
    stuSet.add(stu); 
    for (Student stu2 : stuSet) {
        System.out.println(stu2); 
        } 
    } 
}
        
        
执行结果:Student [name=郭德纲, age=44] 
          Student [name=于谦, age=43] 
          Student [name=郭麒麟, age=23]

 

  总结:equal()准确但是效率低,hashcode()效率高但不准确。

       

posted @ 2020-02-07 21:28  你我皆牛马  阅读(289)  评论(0编辑  收藏  举报