Java HashMap中put与get的工作原理

  1. 一、Put :

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

    /**

      * 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>.)

      */

     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;

     }

  2. 2

    现在我们一步一步来分析上面的代码。

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

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

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

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

    · 如果在刚才计算出来的索引位置没有元素,直接把Entry对象放在那个索引上。

    · 如果索引上有元素,然后会进行迭代,一直到Entry->next是null。当前的Entry对象变成链表的下一个节点。

    · 如果我们再次放入同样的key会怎样呢?逻辑上,它应该替换老的value。事实上,它确实是这么做的。在迭代的过程中,会调用equals()方法来检查key的相等性(key.equals(k)),如果这个方法返回true,它就会用当前Entry的value来替换之前的value。

  3. 3

    Get:

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

    /**

      * 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 http://www.heyzc.com/pro/45.html

      * 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;

     }

  4. 4

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

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

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

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

    在获取了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()方法根本一点用也没有

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值