在集合框架的HashMap.put(Entry k)实现中for循环的目的是什么?

时间:2014-10-01 15:21:25

标签: java collections

我对HashMap JDK实现的理解是,要放在HashMap桶中的Entry对象的Key用于在HashMap对象的Entry []表字段中查找一个位置。 如果是这种情况,为什么该哈希码被用作for循环的起点?如果根据Key中计算出的Hash在预期位置找不到Entry,那么循环遍历Entry对象数组的理由是什么?

OpenJDK中此方法的代码如下。

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 n

1 个答案:

答案 0 :(得分:2)

哈希表如何处理哈希冲突。可以存在多个对象,其哈希码映射到同一个桶。每个桶都包含一个链接的对象列表。