重写 equals() 方法时,重写 hashCode() 方法的必要性

一般来说,我们在其它类中重写 equals() 方法时,一般也要重写 hashCode() 方法,equals() 方法是用来判断两个对象是否相等,那 hashCode() 方法的作用是什么呢?

hashCode() 方法的作用是获取哈希码,也称为散列码;它实际上是返回一个 int 整数。这个哈希码的作用是确定该对象在哈希表中的索引位置。

hashCode() 方法定义在 java.lang 包下的 Object 类中,这是所有类的顶级父类,所以任何类都可以调用到 hashCode() 方法。

 

当两个对象使用 equals() 方法进行比较,返回结果为 true 时,此时说明这两个对象是相等的,那么这两个对象在调用 hashCode() 方法时返回的结果应该也是相同的。

那么实际结果会是怎么样的呢?我们用代码验证一下。

public class Student {

    private String name;  //当名称一样,可以认为两个对象是相等的

    public Student(String name){
        this.name=name;
    }

    /**
     * 重写 Object 中的 equals() 方法
     * @param object
     * @return
     */
    public boolean equals(Object object){

        if (object instanceof Student){

            Student student=(Student)object;

            if (this == student){  //两个对象的地址相同,则它们是相同的
                return true;
            }

            if (this.name.equals(student.name)){  //两个对象的name值相同,也认为它们是相同的
                return true;
            }
        }

        return false;
    }

}

测试代码:

public static void main(String[] args) {

        Student s1=new Student("张三");
        Student s2=new Student("张三");

        System.out.println(s1.equals(s2));

        System.out.println(s1.hashCode());
        System.out.println(s2.hashCode());
    }

运行结果:

true
356573597
1735600054

从上面的运行结果可以看到,s1和s2是相等的,但是他们的散列码不是相同的。

现在我们在 Student 类中重写 hashCode() 方法。

   /**
     * 重写 Object 中的 hashCode() 方法
     * @return
     */
    public int hashCode(){
        return this.name.hashCode();
    }

再次运行测试代码,运行结果为:

true
774889
774889

现在的散列码结果是相同的了。

 

posted @ 2018-12-20 14:30  ____Peanut  阅读(217)  评论(0)    收藏  举报