java_hashmap原理

HashMap整体结构

HashMap由数组+链表组成的,数组是HashMap的主体,链表则是主要为了解决哈希冲突而存在的,
如果定位到的数组位置不含链表(当前entry的next指向null),那么对于查找,添加等操作很快,仅需一次寻址即可;
如果定位到的数组包含链表,对于添加操作,其时间复杂度依然为O(1),因为最新的Entry会插入链表头部,急需要简单改变引用链即可,
而对于查找操作来讲,此时就需要遍历链表,然后通过key对象的equals方法逐一比对查找。所以,性能考虑,HashMap中的链表出现越少,性能才会越好。


package hash;

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() {
        System.out.println(this.name.length()+"-----------");
        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;
    }
}

 1 package hash;
 2 
 3 import java.util.HashMap;
 4 import java.util.Iterator;
 5 
 6 public class HashMapStructure {
 7 
 8     /**
 9      * @param args
10      */
11     public static void main(String[] args) {
12         // TODO Auto-generated method stub
13         Country india = new Country("India", 1000);
14         Country japan = new Country("Japan", 10000);
15 
16         Country france = new Country("France", 2000);
17         Country russia = new Country("Russia", 20000);
18 
19         HashMap<Country, String> countryCapitalMap = new HashMap<Country, String>();
20         countryCapitalMap.put(india, "Delhi");
21         countryCapitalMap.put(japan, "Tokyo");
22         countryCapitalMap.put(france, "Paris");
23         countryCapitalMap.put(russia, "Moscow");
24 
25         Iterator<Country> countryCapitalIter = countryCapitalMap.keySet()
26                 .iterator();// put debug point at this line
27         while (countryCapitalIter.hasNext()) {
28             Country countryObj = countryCapitalIter.next();
29             String capital = countryCapitalMap.get(countryObj);
30             System.out.println(countryObj.getName() + "----" + capital);
31         }
32     }
33 
34 }

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

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

1 static class Entry implements Map.Entry
2 {
3         final K key;
4         V value;
5         Entry next;//存储指向下一个Entry的引用,单链表结构
6         final int hash;//对key的hashcode值进行hash运算后得到的值,存储在Entry,避免重复计算
7         ...//More code goes here
8 }

3. 每当往hashmap里面存放key-value对的时候,都会为它们实例化一个Entry对象,这个Entry对象就会存储在前面提到的Entry数组table中。

而上面创建的Entry对象将会存放在具体哪个位置(在table中的精确位置),是根据key的hashcode()方法计算出来的hash值(来决定)。hash值用来计算key在Entry数组的索引。

4. 上图中数组的索引10,它有一个叫做HashMap$Entry的Entry对象。 我们往hashmap放了4个key-value对,但是看上去好像只有2个元素!!!

这是因为如果两个元素有相同的hashcode,它们会被放在同一个索引上。问题出现了,该怎么放呢?原来它是以链表(LinkedList)的形式来存储的(逻辑上)。

 HashMap:put方法

 1  public V put(K key, V value) {
 2   if (key == null)
 3    return putForNullKey(value);
 4   int hash = hash(key.hashCode());
 5   int i = indexFor(hash, table.length);
 6   for (Entry<k , V> e = table[i]; e != null; e = e.next) {
 7    Object k;
 8    if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
 9     V oldValue = e.value;
10     e.value = value;
11     e.recordAccess(this);
12     return oldValue;
13    }
14   }
15  
16   modCount++;
17   addEntry(hash, key, value, i);
18   return null;
19  }
  1.     对key做null检查。如果key是null,会被存储到table[0],因为null的hash值总是0。  
  2.    static final int hash(Object key) {
            int h;
            return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
        }
  3.     key的hashcode()方法会被调用,然后计算hash值。hash值用来找到存储Entry对象的数组的索引。有时候hash函数可能写的很不好,所以JDK的设计者添加了另一个叫做hash()的方法,它接收刚才计   算的hash值作为参数。
  4.     indexFor(hash,table.length)用来计算在table数组中存储Entry对象的精确的索引。

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

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

  HashMap:get方法

 1 /**
 2   * Returns the value to which the specified key is mapped, or {@code null}
 3   * if this map contains no mapping for the key.
 4   *
 5   * <p>
 6   * More formally, if this map contains a mapping from a key {@code k} to a
 7   * value {@code v} such that {@code (key==null ? k==null :
 8   * key.equals(k))}, then this method returns {@code v}; otherwise it returns
 9   * {@code null}. (There can be at most one such mapping.)
10   *
11   * </p><p>
12   * A return value of {@code null} does not <i>necessarily</i> indicate that
13   * the map contains no mapping for the key; it's also possible that the map
14   * explicitly maps the key to {@code null}. The {@link #containsKey
15   * containsKey} operation may be used to distinguish these two cases.
16   *
17   * @see #put(Object, Object)
18   */
19  public V get(Object key) {
20   if (key == null)
21    return getForNullKey();
22   int hash = hash(key.hashCode());
23   for (Entry<k , V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) {
24    Object k;
25    if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
26     return e.value;
27   }
28   return null;
29  }

当传递一个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。

摘要:

  1. HashMap有一个叫做Entry的内部类,它用来存储key-value对。
  2. 上面的Entry对象是存储在一个叫做table的Entry数组中。
  3. table的索引在逻辑上叫做“桶”(bucket),它存储了链表的第一个元素。
  4. key的hashcode()方法用来找到Entry对象所在的桶。
  5. 如果两个key有相同的hash值,他们会被放在table数组的同一个桶里面。
  6. key的equals()方法用来确保key的唯一性。
  7. value对象的equals()和hashcode()方法根本一点用也没有

 (以上部分内容摘自:微信公众号Java团长-Java HashMap的工作原理)

原文地址:https://www.cnblogs.com/0914lx/p/8275232.html