HashMap的原理

面试的时候经常会遇见诸如:“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
package org.arpit.javapostsforlearning;
public class Country {
 
  String name;
  long population;
 
  public Country(String name, long population) {
   super ();
   this .name = name;
   this .population = population;
  }
  public String getName() {
   return name;
  }
  public void setName(String name) {
   this .name = name;
  }
  public long getPopulation() {
   return population;
  }
  public void setPopulation( long population) {
   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
  public int hashCode() {
   if ( this .name.length()% 2 == 0 )
    return 31 ;
   else
    return 95 ;
  }
  @Override
  public boolean equals(Object obj) {
 
   Country other = (Country) obj;
    if (name.equalsIgnoreCase((other.name)))
    return true ;
   return false ;
  }
 
}

如果想了解更多关于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
import java.util.HashMap;
import java.util.Iterator;
   
public class HashMapStructure {
   
     /**
      * @author Arpit Mandliya
      */
     public static void main(String[] args) {
           
         Country india= new Country( "India" , 1000 );
         Country japan= new Country( "Japan" , 10000 );
           
         Country france= new Country( "France" , 2000 );
         Country russia= new Country( "Russia" , 20000 );
           
         HashMap<country,string> countryCapitalMap= new HashMap<country,string>();
         countryCapitalMap.put(india, "Delhi" );
         countryCapitalMap.put(japan, "Tokyo" );
         countryCapitalMap.put(france, "Paris" );
         countryCapitalMap.put(russia, "Moscow" );
           
         Iterator<country> 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)。将会看到如下的结构:

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

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

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

1
2
3
4
5
6
7
8
static class Entry implements Map.Entry
{
         final K key;
         V value;
         Entry next;
         final int hash;
         ... //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>

`

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

所以,现在假如你已经很好地了解了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 <tt>key</tt>, or <tt>null</tt>
   *         if there was no mapping for <tt>key</tt>. (A <tt>null</tt> return
   *         can also indicate that the map previously associated
   *         <tt>null</tt> with <tt>key</tt>.)
   */
  public V put(K key, V value) {
   if (key == null )
    return putForNullKey(value);
   int hash = hash(key.hashCode());
   int i = 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 );
     return oldValue;
    }
   }
 
   modCount++;
   addEntry(hash, key, value, i);
   return null ;
  }

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

  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.
   *
   * <p>
   * 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.)
   *
   * </p><p>
   * A return value of {@code null} does not <i>necessarily</i> 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)
   */
  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的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()方法根本一点用也没有。
原文链接:  javacodegeeks  翻译:  ImportNew.com  miracle1919
译文链接:  http://www.importnew.com/10620.html
<think>好的,我现在需要详细解释哈希映射(HashMap)的数据结构原理。首先,我得回想一下自己对HashMap的理解,并确保覆盖所有关键点。用户提供的引用内容中提到了哈希表作为底层结构、哈希函数、冲突处理等,这些都是需要涵盖的。 首先,HashMap的基本结构是什么?它基于哈希表,使用数组来存储键值对。哈希函数将键转换为数组的索引,这样可以直接访问对应位置的数据。这里要解释哈希函数的作用,比如将任意大小的数据映射到固定大小的值,作为数组下标。 接下来,哈希冲突是不可避免的,因为不同的键可能生成相同的哈希值。如何处理冲突?常见的方法有开放寻址法和链地址法。根据引用中的内容,用户可能已经提到过链地址法,即每个数组位置是一个链表,存放所有哈希冲突的键值对。需要详细说明这个过程,比如当发生冲突时,将新元素添加到链表中。 然后,需要讨论哈希函数的设计。好的哈希函数应该均匀分布键,以减少冲突。可能提到取模运算,比如用键的哈希值对数组长度取模得到索引。但数组的长度通常选择质数,以减少重复,比如引用中可能提到的。 扩容机制也是一个关键点。当元素数量超过负载因子(比如0.75)时,数组需要扩容,通常翻倍,并重新哈希所有元素到新的数组中。这会影响到性能,但能保持低冲突率。需要解释负载因子的作用和扩容的过程。 另外,时间复杂度方面,理想情况下,插入、删除、查找都是O(1),但最坏情况下(比如所有键冲突)退化为O(n)。所以强调良好的哈希函数和扩容策略的重要性。 可能还需要提到HashMap的应用场景,比如缓存、字典实现等,但用户主要问的是原理,这部分可以简要带过或者放在相关问题里。 现在检查是否有遗漏的部分。引用1提到C语言实现,引用2讲工作原理,引用3提到哈希表和HashMap的实现方法。所以需要综合这些信息,确保覆盖哈希表结构、哈希函数、冲突处理、扩容机制。 需要确保使用正确的中文术语,比如“链地址法”而不是“链表法”。另外,按照系统级指令,行内数学表达式用$...$,比如哈希函数h(key) = key % capacity,这里的公式需要用符号表示,可能需要用LaTeX格式。 在解释过程中,要自然引用提供的引用内容,比如在提到哈希表作为底层结构时引用[^1],在解释哈希函数时引用[^2],在冲突处理时引用[^3]。 最后,生成相关问题,这些问题应该与HashMap原理相关,比如哈希函数设计、冲突处理比较、扩容机制的影响、线程安全等,确保问题有针对性,帮助用户进一步学习。 总结思考步骤: 1. 定义和基本结构:哈希表、键值对存储。 2. 哈希函数的作用和设计。 3. 冲突处理方法,特别是链地址法。 4. 扩容机制和负载因子。 5. 时间复杂度分析。 6. 引用相关文献。 7. 生成相关问题。 现在将这些点组织成连贯的解释,确保符合用户的要求,结构清晰,分点说明,并正确使用格式。</think>### 哈希映射(HashMap)数据结构原理分步解释 #### 1. **基本结构** 哈希映射的核心是**哈希表**,它是一个数组结构,每个位置称为一个“桶”(Bucket)。每个桶存储键值对(Key-Value Pair)的集合。例如,一个容量为10的数组,索引为$0$到$9$,每个索引对应一个桶。 #### 2. **哈希函数** 哈希函数将键(Key)转换为数组索引,公式为: $$ \text{index} = h(\text{key}) \% \text{capacity} $$ 其中$h(\text{key})$是键的哈希值,$\text{capacity}$是数组容量。例如,若键为`"apple"`,哈希值为$1234$,容量为$10$,则索引为$1234 \% 10 = 4$。 **设计要求**: - **均匀分布**:减少冲突概率。 - **高效计算**:时间复杂度为$O(1)$。 #### 3. **冲突处理** 不同键可能产生相同的索引(冲突),常用**链地址法**解决: - 每个桶维护一个链表(或红黑树)。 - 冲突时,新键值对追加到链表末尾。 例如,键`"apple"`和`"banana"`同时映射到索引$4$,则链表存储这两个键值对[^3]。 #### 4. **扩容机制** 当元素数量与容量的比值(负载因子,默认$0.75$)超过阈值时,触发扩容: 1. 新建一个容量翻倍的数组。 2. 重新计算所有键的哈希值并分配到新桶。 此过程保证桶的负载降低,维持$O(1)$操作效率[^3]。 #### 5. **时间复杂度** - **理想情况**:插入、查找、删除均为$O(1)$(无冲突)。 - **最坏情况**:所有键冲突,退化为链表遍历$O(n)$。 优化手段包括使用红黑树(Java 8+)将链表操作优化至$O(\log n)$。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值