重写equels()后需重写hashcode()的意义

    技术2022-05-19  19

    sun对于eqauls方法和hashCode方法是这样规定的: 1、如果两个对象相同,那么它们的hashCode值一定要相同;

    2、如果两个对象的hashCode相同,它们并不一定相同。(例如:String类)

     

    它的意义在于:

    在集合类中例如Set的要求是,不能有重复的元素出现在集合中。

    判断不重复的过程:首先比较的是hashcode,若相同再调用此对象的equals()方法做判断。

    所以,为了提升集合类的性能 ,在重写equels()时有必要重写hashcode(),这样就能在比较hashcode后以很快的速度做出判断是否为重复的元素。

     

    例外:

    这仅仅是一个规定,eqauls()返回true,hashcode也可以不同。

    public class Person { private static int i = 0; @Override public boolean equals(Object obj) { return true; } @Override public int hashCode() { return i++; } public static void main(String[] args) { Person person1 = new Person(); Person person2 = new Person(); System.out.println(person1.equals(person2)); //输出true System.out.println(person1.hashCode()==person2.hashCode()); //输出false } }

     

     


    最新回复(0)