先以一段代码开始这篇blog。

01 public class Name {
02  
03   private String first; //first name
04   private String last;  //last name
05  
06   public String getFirst() {
07     return first;
08   }
09  
10   public void setFirst(String first) {
11     this.first = first;
12   }
13  
14   public String getLast() {
15     return last;
16   }
17  
18   public void setLast(String last) {
19     this.last = last;
20   }
21  
22   public Name(String first, String last) {
23     this.first = first;
24     this.last = last;
25   }
26  
27   @Override
28   public boolean equals(Object object) {
29     Name name = (Name) object;
30  
31     return first.equals(name.getFirst()) && last.equals(name.getLast());
32   }
33  
34   public static void main(String[] args) {
35     Map<Name, String> map = new HashMap<Name, String>();
36     map.put(new Name("mali", "sb"), "yes");
37      
38     System.out.println("is the key existed? ture or false? -> "
39         + map.containsKey(new Name("mali", "sb")));
40   }
41  
42 }

那输出结果是什么呢?类似这样的题目总能遇到,以前不知道有什么好考的,弱智?自己动手尝试了一次,发现结果不是自己想象的那样。本篇就用来揭示HashMap的equals与hashCode中你不知道的秘密。结果如下:

is the key existed? ture or false? -> false

对的,结果就是false,我很不理解为什么这样,已经重写了equals函数了啊!当时真心不服气,就在equals函数里面打了断点,然后更让我难以置信的事情发生了,断点处没有停。非常困惑,不过还好,jdk的源码在手上,去查了HashMap中containsKey函数的源码。源码结构如下图:

从图中可以看出,真正干活的是getEntry(Object key),重点看如下两行:

1 if (e.hash == hash &&
2                 ((k = e.key) == key || (key != null && key.equals(k))))
3     return e;

从if条件上看,是一个短路与,首先要判断两个对象的hash值是否相等。如果相等才进行后续的判断。或者换一个说法,在HashMap中只有两个对象的hash值相等的前提下才会执行equals方法的逻辑。关于这一点,有两个佐证。

在stackoverflow上找到一篇关于HashMap不执行equals方法的文章,回答中有明确给出这样的答案。Java HashMap.containsKey() doesn’t call equals()

自己编程验证。

在文章开头的基础上,做了点儿改进,输出两个对象的hash值,并且在equals方法中打印一行文字。如下:

01 public class Name {
02  
03   private String first; //first name
04   private String last;  //last name
05  
06   public String getFirst() {
07     return first;
08   }
09  
10   public void setFirst(String first) {
11     this.first = first;
12   }
13  
14   public String getLast() {
15     return last;
16   }
17  
18   public void setLast(String last) {
19     this.last = last;
20   }
21  
22   public Name(String first, String last) {
23     this.first = first;
24     this.last = last;
25   }
26  
27   @Override
28   public boolean equals(Object object) {
29     System.out.println("equals is running...");
30     Name name = (Name) object;
31  
32     return first.equals(name.getFirst()) && last.equals(name.getLast());
33   }
34  
35   public static void main(String[] args) {
36     Map<Name, String> map = new HashMap<Name, String>();
37     Name n1 = new Name("mali", "sb");
38     System.out.println("the hashCode of n1 : " + n1.hashCode());
39     map.put(n1, "yes");
40     Name n2 = new Name("mali", "sb");
41     System.out.println("the hashCode of n2 : " + n2.hashCode());
42     System.out.println("is the key existed? ture or false? -> "
43         + map.containsKey(n2));
44   }
45  
46 }

结果:

the hashCode of n1 : 1690552137

the hashCode of n2 : 1901116749

is the key existed? ture or false? -> false

从执行结果可以看出1、两个对象的hash值是不相同的;2、equals方法确实也没有执行。

再次对代码进行改进,加入重写的hashCode方法,如下,看看这次的结果会是怎样。

01 public class Name {
02  
03   private String first; //first name
04   private String last;  //last name
05  
06   public String getFirst() {
07     return first;
08   }
09  
10   public void setFirst(String first) {
11     this.first = first;
12   }
13  
14   public String getLast() {
15     return last;
16   }
17  
18   public void setLast(String last) {
19     this.last = last;
20   }
21  
22   public Name(String first, String last) {
23     this.first = first;
24     this.last = last;
25   }
26  
27   @Override
28   public boolean equals(Object object) {
29     System.out.println("equals is running...");
30     Name name = (Name) object;
31  
32     return first.equals(name.getFirst()) && last.equals(name.getLast());
33   }
34  
35   public int hashCode() {
36     System.out.println("hashCode is running...");
37     return first.hashCode() + last.hashCode();
38   }
39  
40   public static void main(String[] args) {
41     Map<Name, String> map = new HashMap<Name, String>();
42     Name n1 = new Name("mali", "sb");
43     System.out.println("the hashCode of n1 : " + n1.hashCode());
44     map.put(n1, "yes");
45     Name n2 = new Name("mali", "sb");
46     System.out.println("the hashCode of n2 : " + n2.hashCode());
47     System.out.println("is the key existed? ture or false? -> "
48         + map.containsKey(n2));
49   }
50  
51 }

结果:

hashCode is running...

the hashCode of n1 : 3347552

hashCode is running...

hashCode is running...

the hashCode of n2 : 3347552

hashCode is running...

equals is running...

is the key existed? ture or false? -> true

同样从结果中可以看出:在hash值相等的情况下,equals方法也执行了,HashMap的containsKey方法也像预想的那样起作用了。

结论:

在使用HashSet(contains也是调用HashMap中的方法)、HashMap等集合时,如果用到contains系列方法时,记得需同时重写equals与hashCode方法。

HashMap之equals和hashCode小陷阱的更多相关文章

  1. Java中equals,hashcode

         在Java语言中,Object对象中包含一个equals和hashCode方法,其中hashCode方法是由JVM本地代码(native code)实现的,返回值是一个有符号的32位整数,对 ...

  2. [转载] HashMap的工作原理-hashcode和equals的区别

    目录 前言 为什么需要使用Hashcode,可以从Java集合的常用需求来描述: 更深入的介绍 先来些简单的问题 HashMap的0.75负载因子 总结 我在网上看到的这篇文章,介绍的很不错,但是我看 ...

  3. == 和 equals,equals 与 hashcode,HashSet 和 HashMap,HashMap 和 Hashtable

    一:== 和 equals == 比较引用的地址equals 比较引用的内容 (Object 类本身除外) String obj1 = new String("xyz"); Str ...

  4. 堆、栈、内存分配、==、equals、hashcode详解(转载)

    问题的引入: 问题一:String str1 = "abc";String str2 = "abc";System.out.println(str1==str2 ...

  5. 如何在Java中避免equals方法的隐藏陷阱

    摘要 本文描述重载equals方法的技术,这种技术即使是具现类的子类增加了字段也能保证equal语义的正确性. 在<Effective Java>的第8项中,Josh Bloch描述了当继 ...

  6. Java == ,equals 和 hashcode 的区别和联系(阿里面试)

    今天阿里的人问我 equals 与hashcode的区别,我答不上来, 仔细查了一下,做了总结: (1) == 这是Java 比较内存地址,就是内存中的对象: java中的==是比较两个对象在JVM中 ...

  7. Object之equals和hashCode

    译者注 :你可能会觉得Java很简单,Object的equals实现也会非常简单,但是事实并不是你想象的这样,耐心的读完本文,你会发现你对Java了解的是如此的少.如果这篇文章是一份Java程序员的入 ...

  8. 关于重写equals()和hashCode()的思考

    最近这几天一直对equals()和hashCode()的事搞不清楚,云里雾里的. 为什么重写equals(),我知道. 但是为什么要两个都要重写呢,我就有点迷糊了,所以趁现在思考清楚后记录一下. 起因 ...

  9. 如何编写出高质量的 equals 和 hashcode 方法?

    什么是 equals 和 hashcode 方法? 这要从 Object 类开始说起,我们知道 Object 类是 Java 的超类,每个类都直接或者间接的继承了 Object 类,在 Object ...

随机推荐

  1. 测试环境docker化—容器集群编排实践

    本文来自网易云社区 作者:孙婷婷 背景 在前文<测试环境docker化-基于ndp部署模式的docker基础镜像制作>中已经详述了docker镜像制作及模块部署的过程,按照上述做法已可以搭 ...

  2. jquery实现轮播插件

    这几天用jquery写了两个轮播的插件,功能很简单.第一次尝试写插件,有很多不足的地方,代码如下: 注:图片链接请替换掉,配置信息必须加上图片width和height. <!DOCTYPE ht ...

  3. Python-S9——Day109-Git及Redis

    1.初识Git: 2.Git版本控制之stash和branch: 1.初识Git: 1.1 Git是什么? Git是一个用于帮助用户实现“版本控制”的软件: 1.2 Git安装: GIt官网:http ...

  4. Leetcode with Python -> Array

    118. Pascal's Triangle Given numRows, generate the first numRows of Pascal's triangle. For example, ...

  5. idea项目多模项目的搭建(复制)

    本文通过一个例子来介绍利用maven来构建一个多模块的jave项目.开发工具:intellij idea. 一.项目结构 multi-module-PRoject是主工程,里面包含两个模块(Modul ...

  6. 软件包管理rpm_yum

    和文本相关的命令cat 正向显示文本tac 反向显示文本more 可以一步一步显示文本文件less 还可以往上看.几个快捷键:j(往下看), k (往上看), g(定位最上), G(定位最下), ct ...

  7. 大素数判断和素因子分解(miller-rabin,Pollard_rho算法)

    #include<stdio.h> #include<string.h> #include<stdlib.h> #include<time.h> #in ...

  8. 基于Linux的嵌入式文件系统构建与设计

    摘 要:Linux是当今一种十分流行的嵌入式操作系统.由于其具有执行效率高.占用空间小.实时性能优良和可扩展性强等特点,因此被广泛应用于工业控制领域.该文对其文件系统进行了简单的介绍,结合嵌入式系统应 ...

  9. 刷题总结——Collecting Bugs(poj2096)

    题目: Description Ivan is fond of collecting. Unlike other people who collect post stamps, coins or ot ...

  10. 替换/重制Homebrew源

    homebrew主要分两部分:git repo(位于GitHub)和二进制bottles(位于bintray),这两者在国内访问都不太顺畅.可以替换成国内的镜像,git repo国内镜像就比较多了,可 ...