Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 集合框架的HashMap.put(条目k)实现中for循环的目的是什么?_Java_Collections - Fatal编程技术网

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

Java 集合框架的HashMap.put(条目k)实现中for循环的目的是什么?,java,collections,Java,Collections,我对HashMap JDK实现的理解是,要放在HashMap bucket中的Entry对象的键用于在HashMap对象的Entry[]表字段中找到一个位置。 如果是这种情况,为什么要将该哈希代码用作for循环的起点?如果根据从键计算的散列在预期位置找不到条目,则循环遍历条目对象数组的基本原理是什么 下面是来自OpenJDK的此方法的代码 public V put(K key, V value) { if (key == null) ret

我对HashMap JDK实现的理解是,要放在HashMap bucket中的Entry对象的键用于在HashMap对象的Entry[]表字段中找到一个位置。 如果是这种情况,为什么要将该哈希代码用作for循环的起点?如果根据从键计算的散列在预期位置找不到条目,则循环遍历条目对象数组的基本原理是什么

下面是来自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
public V put(K键,V值){
if(key==null)
返回putForNullKey(值);
int hash=hash(key.hashCode());
int i=indexFor(散列,table.length);
for(条目e=表[i];e!=null;e=e.next){
对象k;
如果(e.hash==hash&((k=e.key)==key | | key.equals(k))){
V oldValue=e.value;
e、 价值=价值;
e、 记录存取(本);
返回旧值;
}
}
modCount++;
加法器(散列、键、值、i);
返回n

这是哈希表处理哈希冲突的方式。可以有多个对象的哈希代码映射到同一个bucket。每个bucket都包含一个对象的链接列表。

bucket是链接列表。