简体   繁体   English

HasMap的实现是否将键值对存储在链表中

[英]Does the implementation of HasMap store key-value pairs in a linked list

I read in a book where it was mentioned that when we put elements in HashMap, internally it is stored in bucket.我在一本书中读到,当我们将元素放入 HashMap 时,它在内部存储在存储桶中。 My question is我的问题是

  1. Does hashmap store key-value pair altogether in the form of linked list? hashmap 是否完全以链表的形式存储键值对? or does it store in linked list only when there is a collision?还是仅在发生冲突时才存储在链表中?

  2. How does it retrieve the object when 2 different objects are stored in the same bucket?当 2 个不同的对象存储在同一个存储桶中时,它如何检索 object?

Thanks!谢谢!

Lots of details at http://en.wikipedia.org/wiki/Hash_table http://en.wikipedia.org/wiki/Hash_table上有很多细节

See also Internal implementation of java.util.HashMap and HashSet另见java.util.HashMap 和 HashSet 的内部实现

And of course you can use the source , Luke.当然,您可以使用,卢克。

Updated: to specifically answer your Q, it stores an Entry, which has a reference to the next item in the bucket (if any).更新:为了专门回答您的 Q,它存储了一个条目,其中包含对存储桶中下一个项目的引用(如果有)。 If there is only one item in the bucket then the reference will be null:如果存储桶中只有一项,则引用将为 null:

static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next;

The data type of the bucket Array is Map.Entry . bucket Array 的数据类型为Map.Entry When multiple entries fall in the same bucket they are stored in what is conceptually a unidirectional linked list, by holding references to the next Entry.当多个条目落在同一个桶中时,它们通过保存对下一个条目的引用存储在概念上的单向链表中。 Just the Entry at the 'head' is inside the array that is the buckets.只有“头部”的条目位于存储桶数组内。 However, there is never any use a java.util.LinkedList or some actual list class.但是,从来没有使用过java.util.LinkedList或某些实际列表 class。 The entries just form a list in and of themselves by holding references to their bucket-mates.这些条目只是通过保存对它们的桶友的引用来形成一个列表。

When there's more than one in a bucket, it starts with the one that's actually in the Map.Entry[] , which is the head of the list, and just starts traversing and checking .equals() until it finds a match or next is null.当存储桶中有多个时,它从Map.Entry[]中实际存在的那个开始,它是列表的头部,然后开始遍历和检查.equals()直到找到匹配项或下一个null。

Best way to understand is by tracing source最好的理解方法是溯源

  • In eclipse If configured jdk hit ctrl+shift+T type HashMap and AbstractMap在 eclipse 如果配置 jdk 打ctrl+shift+T类型HashMapAbstractMap
  • AbstractMap and HashMap AbstractMapHashMap

You only need to do it once !你只需要做一次!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM