hashCode和equals方法的理解

1.介绍

1.1 equals方法

equals方法是Object对象中定义的方法,该方法的原意是:比较的两个对象内容/值是否相等。

Object.equals方法默认实现的是用==,即比较是否指向同一个对象:

public class Object {
    //...
    public boolean equals(Object obj) {
        return (this == obj);
    }
    //...
}

1.2 hashCode方法

JavaDoc对hashcode方法的介绍:

Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by java.util.HashMap.
The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java™ programming language.)

翻译结果:

返回对象的哈希码值。设计此方法目的是为了哈希表所服务的,例如java.util.HashMap提供的哈希表。hashCode的一般约定为:

  • 在Java应用程序的执行过程中,只要在同一对象上多次调用它,则hashCode方法必须一致地返回相同的整数,前提是未修改该对象的equals比较中使用的信息。从一个应用程序的执行到同一应用程序的另一执行,此整数不必保持一致。
  • 如果根据equals(Object)方法,两个对象相等,则在两个对象中的每个对象上调用hashCode方法必须产生相同的整数结果。
  • 根据equals(Object)方法,如果两个对象不相等,则不需要在两个对象中的每个对象上调用hashCode方法必须产生不同的整数结果。但是,程序员应该意识到,为不相等的对象生成不同的整数结果可能会提高哈希表的性能。

在合理可行的范围内,由Object类定义的hashCode方法确实为不同的对象返回不同的整数。 (通常通过将对象的内部地址转换为整数来实现,但是Java™编程语言不需要此实现技术。)

hashCode方法也是Obejct对象所定义的,它存在的意义就是为哈希表所服务,但是此方法定义了几个约束条件,总结地来说就两条,也是任何Java程序员必须掌握的两条规则:

两个对象的hashcode相同,其值不一定相等。
两个对象的值相等,必须要使hashcode相等。

Object的hashCode方法默认实现是native的:

public class Object {
    //...
    public native int hashCode();
    //...
}

两个对象的hashcode相同,其值不一定相等的例子:

public class HashTest {
  public static void main(String[] args) {
    String s = "a";
    Integer aInt = 97;
    System.out.println(s.hashCode()); // 97
    System.out.println(aInt.hashCode()); // 97
  }
}

2. 实战案例

2.1 背景介绍

创建一个User对象,里面拥有一个name和age属性,按照业务要求,内容属性值相等则两个对象就相等,请重写equals和hashCode方法。

public class User {
  private String name;
  private Integer age;

  public User(String name, Integer age) {
    this.name = name;
    this.age = age;
  }
  
  // getter and setter
}

2.2 重写equals

  @Override
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null) {
      return false;
    }
    if (this.getClass() != obj.getClass()) {
      return false;
    }
    User target = (User) obj;
    return this.name.equals(target.getName()) && this.age.equals(target.getAge());
  }

2.3 重写hashCode

  @Override
  public int hashCode() {
    int result = 17;
    result = 31 * result + (name == null? 0: name.hashCode());
    result = 31 * result + (age == null? 0: age.hashCode());
    return result;
  }

3. 面试题

3.1 重写equals方法为什么一定要重写hashcode方法?

浅层次解读:

从出处来讲:这是Object对象的JavaDoc中为equals方法定义的约定条件。
从使用角度来讲:hashCode为像HashMap等使用哈希表的对象提供服务。是怎么提供服务的呢?请看深层次解读。

深层次解读:

当使用hashmap的put方法时,如果key为我们定义的对象,
那么计算hashmap的bucket/槽位时就需要调用key对象的hashcode方法,
也就是说key对象的hashcode方法就决定了存储在map中的bucket位置,
要是两个对象值相等(只重写了equals方法而没有重写hashcode方法的话),
就无法保证两个对象落在同一个bucket中,从而导致容器不可用。

HashMap计算key的规则和方法:

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
    
    static final int hash(Object key) {
        int h;
        // 调用了key对象的hashCode方法
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

示例:

  • 只重写equals而没重写hashCode导致的查询问题:
public class HashTest {
  public static void main(String[] args) {
    HashMap<User, String> map = new HashMap<>();
    User user1 = new User("Tom", 20);
    User user2 = new User("Tom", 20);
    map.put(user1, user1.getName() + ":" + user1.getAge());
    System.out.println(map.get(user2)); // null
    System.out.println(map.containsKey(user2)); // false
  }
}

由于user1和user2内容相同,按照业务需求,往map中存了user1,那么用user2去查也就应该是可以查得到内容的。

  • 重写equlas和hashCode方法,业务正常:
public class HashTest {
  public static void main(String[] args) {
    HashMap<User, String> map = new HashMap<>();
    User user1 = new User("Tom", 20);
    User user2 = new User("Tom", 20);
    map.put(user1, user1.getName() + ":" + user1.getAge());
    System.out.println(map.get(user2)); // Tom:20
    System.out.println(map.containsKey(user2)); // true
  }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270