equals方法和hashCode方法

来源:互联网 发布:网吧网络为什么不卡 编辑:程序博客网 时间:2024/06/05 11:27

在有些情况下,程序设计者在设计一个类的时候为需要重写equals方法,比如String类,但是千万要注意,在重写equals方法的同时,必须重写hashCode方法。为什么这么说呢?

请下面看一个例子:

package com.cxh.test1;import java.util.HashMap;import java.util.HashSet;import java.util.Set;class People{    private String name;    private int age;    public People(String name,int age) {        this.name = name;        this.age = age;    }      public void setAge(int age){        this.age = age;    }    @Override    public boolean equals(Object obj) {        // TODO Auto-generated method stub        return this.name.equals(((People)obj).name) && this.age== ((People)obj).age;    }}public class Main {    public static void main(String[] args) {        People p1 = new People("Jack", 12);        System.out.println(p1.hashCode());        HashMap<People, Integer> hashMap = new HashMap<People, Integer>();        hashMap.put(p1, 1);        System.out.println(hashMap.get(new People("Jack", 12)));    }}

在这里我只重写了equals方法,也就说如果两个People对象,如果它的姓名和年龄相等,则认为是同一个人。

这段代码本来的意愿是想这段代码输出结果为“1”,但是事实上它输出的是“null”。为什么呢?原因就在于重写equals方法的同时忘记重写hashCode方法。

虽然通过重写equals方法使得逻辑上姓名和年龄相同的两个对象被判定为相等的对象(跟String类类似),但是要知道默认情况下,hashCode方法是将对象的存储地址进行映射。那么上述代码的输出结果为“null”就不足为奇了。原因很简单,p1指向的对象和

System.out.println(hashMap.get(new People(“Jack”, 12)));这句中的new People(“Jack”, 12)生成的是两个对象,它们的存储地址肯定不同。下面是HashMap的get方法的具体实现:

public V get(Object key) {        if (key == null)            return getForNullKey();        int hash = hash(key.hashCode());        for (Entry<K,V> e = table[indexFor(hash, table.length)];             e != null;             e = e.next) {            Object k;            if (e.hash == hash && ((k = e.key) == key || key.equals(k)))                return e.value;        }        return null;    }

所以在hashmap进行get操作时,因为得到的hashcdoe值不同(注意,上述代码也许在某些情况下会得到相同的hashcode值,不过这种概率比较小,因为虽然两个对象的存储地址不同也有可能得到相同的hashcode值),所以导致在get方法中for循环不会执行,直接返回null。

因此如果想上述代码输出结果为“1”,很简单,只需要重写hashCode方法,让equals方法和hashCode方法始终在逻辑上保持一致性。

package com.cxh.test1;import java.util.HashMap;import java.util.HashSet;import java.util.Set;/** */ class People{    private String name;    private int age;    public People(String name,int age) {        this.name = name;        this.age = age;    }      public void setAge(int age){        this.age = age;    }    @Override    public int hashCode() {        // TODO Auto-generated method stub        return name.hashCode()*37+age;    }    @Override    public boolean equals(Object obj) {        // TODO Auto-generated method stub        return this.name.equals(((People)obj).name) && this.age== ((People)obj).age;    }}public class Main {    public static void main(String[] args) {        People p1 = new People("Jack", 12);        System.out.println(p1.hashCode());        HashMap<People, Integer> hashMap = new HashMap<People, Integer>();        hashMap.put(p1, 1);        System.out.println(hashMap.get(new People("Jack", 12)));    }}

这样一来的话,输出结果就为“1”了。

下面这段话摘自Effective Java一书:

在程序执行期间,只要equals方法的比较操作用到的信息没有被修改,那么对这同一个对象调用多次,hashCode方法必须始终如一地返回同一个整数。如果两个对象根据equals方法比较是相等的,那么调用两个对象的hashCode方法必须返回相同的整数结果。如果两个对象根据equals方法比较是不等的,则hashCode方法不一定得返回不同的整数。
原创粉丝点击