HashMap.get中的一个循环 [英] A loop in HashMap.get
问题描述
这是一个从HashMap中的键获取值的代码。为什么需要在第317行循环取值?如果这不是O(1)操作?
public V get(Object key){
315 if(key == null)
316返回getForNullKey();
317 int hash = hash(key.hashCode()); (Entry< K,V> e = table [indexFor(hash,table.length)];
319 e!= null;
320 e = e.next){
321对象k;
322 if(e.hash == hash&&((k = e.key)== key || key.equals(k)))
323 return e.value;
324}
325返回null;
326}
HashXXXX
集合包含: -
数组。通过对象的hashCode
-
条目列表将对象分配给数组中的某个位置(存储桶)。由于您可以拥有许多其哈希码指向相同存储桶的条目,因此每个存储桶都包含项目列表。一个新的项目将被添加到该列表中(所以它不会删除以前的项目)。
从第二点开始列出。
This is a code to fetch a value from a key in HashMap. Why does it need to loop on line 317 to fetch the value ? Should this not be an O(1) operation ?
public V get(Object key) {
315 if (key == null)
316 return getForNullKey();
317 int hash = hash(key.hashCode());
318 for (Entry<K,V> e = table[indexFor(hash, table.length)];
319 e != null;
320 e = e.next) {
321 Object k;
322 if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
323 return e.value;
324 }
325 return null;
326 }
The HashXXXX
collections consist of:
an array. An object is assigned to a position in the array (a bucket) by its hashCode
a list of entries. Since you can have many entries whose hashcode points them to the same bucket, each bucket holds a list of items. A new item will be added to that list (so it does not deletes previous items).
The iteration is running along that list from the second point.
这篇关于HashMap.get中的一个循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!