Java HashMap的工作原理

Wesley13
• 阅读 609

面试的时候经常会遇见诸如:“java中的HashMap是怎么工作的”,“HashMap的get和put内部的工作原理”这样的问题。本文将用一个简单的例子来解释下HashMap内部的工作原理。首先我们从一个例子开始,而不仅仅是从理论上,这样,有助于更好地理解,然后,我们来看下get和put到底是怎样工作的。

我们来看个非常简单的例子。有一个”国家”(Country)类,我们将要用Country对象作为key,它的首都的名字(String类型)作为value。下面的例子有助于我们理解key-value对在HashMap中是如何存储的。

1. Country.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

packageorg.arpit.javapostsforlearning;

publicclassCountry {

 String name;

 longpopulation;

 publicCountry(String name,longpopulation) {

  super();

  this.name = name;

  this.population = population;

 }

 publicString getName() {

  returnname;

 }

 publicvoidsetName(String name) {

  this.name = name;

 }

 publiclonggetPopulation() {

  returnpopulation;

 }

 publicvoidsetPopulation(longpopulation) {

  this.population = population;

 }

 // If length of name in country object is even then return 31(any random number) and if odd then return 95(any random number).

 // This is not a good practice to generate hashcode as below method but I am doing so to give better and easy understanding of hashmap.

 @Override

 publicinthashCode() {

  if(this.name.length()%2==0)

   return31;

  else

   return95;

 }

 @Override

 publicbooleanequals(Object obj) {

  Country other = (Country) obj;

   if(name.equalsIgnoreCase((other.name)))

   returntrue;

  returnfalse;

 }

}

如果想了解更多关于Object对象的hashcode和equals方法的东西,可以参考:
java中的hashcode()和equals()方法

2. HashMapStructure.java(main class)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

importjava.util.HashMap;

importjava.util.Iterator;

publicclassHashMapStructure {

    /**

     * @author Arpit Mandliya

     */

    publicstaticvoidmain(String[] args) {

        Country india=newCountry("India",1000);

        Country japan=newCountry("Japan",10000);

        Country france=newCountry("France",2000);

        Country russia=newCountry("Russia",20000);

        HashMap<country,string> countryCapitalMap=newHashMap<country,string>();

        countryCapitalMap.put(india,"Delhi");

        countryCapitalMap.put(japan,"Tokyo");

        countryCapitalMap.put(france,"Paris");

        countryCapitalMap.put(russia,"Moscow");

        Iterator countryCapitalIter=countryCapitalMap.keySet().iterator();//put debug point at this line

        while(countryCapitalIter.hasNext())

        {

            Country countryObj=countryCapitalIter.next();

            String capital=countryCapitalMap.get(countryObj);

            System.out.println(countryObj.getName()+"----"+capital);

            }

        }

}

现在,在第23行设置一个断点,在项目上右击->调试运行(debug as)->java应用(java application)。程序会停在23行,然后在countryCapitalMap上右击,选择“查看”(watch)。将会看到如下的结构:

Java HashMap的工作原理

从上图可以观察到以下几点:

  1. 有一个叫做table大小是16的Entry数组。

  2. 这个table数组存储了Entry类的对象。HashMap类有一个叫做Entry的内部类。这个Entry类包含了key-value作为实例变量。我们来看下Entry类的结构。Entry类的结构:

1

2

3

4

5

6

7

8

staticclassEntryimplementsMap.Entry

{

        finalK key;

        V value;

        Entry next;

        finalinthash;

        ...//More code goes here

}   `

  1. 每当往hashmap里面存放key-value对的时候,都会为它们实例化一个Entry对象,这个Entry对象就会存储在前面提到的Entry数组table中。现在你一定很想知道,上面创建的Entry对象将会存放在具体哪个位置(在table中的精确位置)。答案就是,根据key的hashcode()方法计算出来的hash值(来决定)。hash值用来计算key在Entry数组的索引。

  2. 现在,如果你看下上图中数组的索引10,它有一个叫做HashMap$Entry的Entry对象。

  3. 我们往hashmap放了4个key-value对,但是看上去好像只有2个元素!!!这是因为,如果两个元素有相同的hashcode,它们会被放在同一个索引上。问题出现了,该怎么放呢?原来它是以链表(LinkedList)的形式来存储的(逻辑上)。

上面的country对象的key-value的hash值是如何计算出来的。

`

<code>Japan的Hash值是95,它的长度是奇数。

India的Hash值是95,它的长度是奇数。

Russia的Hash值是31,它的长度是偶数。

France,它的长度是偶数。
</code>

`

下图会清晰的从概念上解释下链表。

Java HashMap的工作原理

所以,现在假如你已经很好地了解了hashmap的结构,让我们看下put和get方法。

Put :

让我们看下put方法的实现:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

/**

  * Associates the specified value with the specified key in this map. If the

  * map previously contained a mapping for the key, the old value is

  * replaced.

  *

  * @param key

  *            key with which the specified value is to be associated

  * @param value

  *            value to be associated with the specified key

  * @return the previous value associated with key, or null

  *         if there was no mapping for key. (A null return

  *         can also indicate that the map previously associated

  *         null with key.)

  */

 publicV put(K key, V value) {

  if(key ==null)

   returnputForNullKey(value);

  inthash = hash(key.hashCode());

  inti = indexFor(hash, table.length);

  for(Entry<k , V> e = table[i]; e !=null; e = e.next) {

   Object k;

   if(e.hash == hash && ((k = e.key) == key || key.equals(k))) {

    V oldValue = e.value;

    e.value = value;

    e.recordAccess(this);

    returnoldValue;

   }

  }

  modCount++;

  addEntry(hash, key, value, i);

  returnnull;

 }

现在我们一步一步来看下上面的代码。

  1. 对key做null检查。如果key是null,会被存储到table[0],因为null的hash值总是0。

  2. key的hashcode()方法会被调用,然后计算hash值。hash值用来找到存储Entry对象的数组的索引。有时候hash函数可能写的很不好,所以JDK的设计者添加了另一个叫做hash()的方法,它接收刚才计算的hash值作为参数。如果你想了解更多关于hash()函数的东西,可以参考:hashmap中的hash和indexFor方法

  3. indexFor(hash,table.length)用来计算在table数组中存储Entry对象的精确的索引。

  4. 在我们的例子中已经看到,如果两个key有相同的hash值(也叫冲突),他们会以链表的形式来存储。所以,这里我们就迭代链表。

  • 如果在刚才计算出来的索引位置没有元素,直接把Entry对象放在那个索引上。
  • 如果索引上有元素,然后会进行迭代,一直到Entry->next是null。当前的Entry对象变成链表的下一个节点。
  • 如果我们再次放入同样的key会怎样呢?逻辑上,它应该替换老的value。事实上,它确实是这么做的。在迭代的过程中,会调用equals()方法来检查key的相等性(key.equals(k)),如果这个方法返回true,它就会用当前Entry的value来替换之前的value。

Get:

现在我们来看下get方法的实现:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

/**

  * Returns the value to which the specified key is mapped, or { @code null}

  * if this map contains no mapping for the key.

  *

  *

  * More formally, if this map contains a mapping from a key { @code k} to a

  * value { @code v} such that { @code (key==null ? k==null :

  * key.equals(k))}, then this method returns { @code v}; otherwise it returns

  * { @code null}. (There can be at most one such mapping.)

  *

  *

  * A return value of { @code null} does not necessarily indicate that

  * the map contains no mapping for the key; it's also possible that the map

  * explicitly maps the key to { @code null}. The { @link #containsKey

  * containsKey} operation may be used to distinguish these two cases.

  *

  * @see #put(Object, Object)

  */

 publicV get(Object key) {

  if(key ==null)

   returngetForNullKey();

  inthash = 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)))

    returne.value;

  }

  returnnull;

 }

当你理解了hashmap的put的工作原理,理解get的工作原理就非常简单了。当你传递一个key从hashmap总获取value的时候:

  1. 对key进行null检查。如果key是null,table[0]这个位置的元素将被返回。

  2. key的hashcode()方法被调用,然后计算hash值。

  3. indexFor(hash,table.length)用来计算要获取的Entry对象在table数组中的精确的位置,使用刚才计算的hash值。

  4. 在获取了table数组的索引之后,会迭代链表,调用equals()方法检查key的相等性,如果equals()方法返回true,get方法返回Entry对象的value,否则,返回null。

要牢记以下关键点:

  • HashMap有一个叫做Entry的内部类,它用来存储key-value对。
  • 上面的Entry对象是存储在一个叫做table的Entry数组中。
  • table的索引在逻辑上叫做“桶”(bucket),它存储了链表的第一个元素。
  • key的hashcode()方法用来找到Entry对象所在的桶。
  • 如果两个key有相同的hash值,他们会被放在table数组的同一个桶里面。
  • key的equals()方法用来确保key的唯一性。
  • value对象的equals()和hashcode()方法根本一点用也没有
点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
2星期前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Easter79 Easter79
2年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Docker 部署SpringBoot项目不香吗?
  公众号改版后文章乱序推荐,希望你可以点击上方“Java进阶架构师”,点击右上角,将我们设为★“星标”!这样才不会错过每日进阶架构文章呀。  !(http://dingyue.ws.126.net/2020/0920/b00fbfc7j00qgy5xy002kd200qo00hsg00it00cj.jpg)  2
Wesley13 Wesley13
2年前
Java HashMap的工作原理
面试的时候经常会遇见诸如:“java中的HashMap是怎么工作的”,“HashMap的get和put内部的工作原理”这样的问题。本文将用一个简单的例子来解释下HashMap内部的工作原理。首先我们从一个例子开始,而不仅仅是从理论上,这样,有助于更好地理解,然后,我们来看下get和put到底是怎样工作的。我们来看个非常简单的例子。有一个”国家”(Coun
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
6个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这