且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

LinkedHashMap 的内部实现与 HashMap 实现有何不同?

更新时间:2023-12-05 13:43:34

所以,它有一个 Entry 对象数组.

不完全是.它有一个 Entry 对象 chains 数组.HashMap.Entry 对象具有 next 字段,允许将 Entry 对象链接为链表.

Not exactly. It has an array of Entry object chains. A HashMap.Entry object has a next field allowing the Entry objects to be chained as a linked list.

我想知道这个数组的索引如何在 hashCode 相同但对象不同的情况下存储多个 Entry 对象.

I was wondering how can an index of this array store multiple Entry objects in case of same hashCode but different objects.

因为(如您问题中的图片所示) Entry 对象是链式的.

Because (as the picture in your question shows) the Entry objects are chained.

这与 LinkedHashMap 实现有何不同?它是 map 的双向链表实现,但它是否像上面一样维护一个数组,它如何存储指向下一个和前一个元素的指针?

How is this different from LinkedHashMap implementation? Its doubly linked list implementation of map but does it maintain an array like the above and how does it store pointers to the next and previous element?

LinkedHashMap 实现中,LinkedHashMap.Entry 类扩展了 HashMap.Entry 类,通过添加 beforeafter 字段.这些字段用于将 LinkedHashMap.Entry 对象组装成一个记录插入顺序的独立双向链表.因此,在 LinkedHashMap 类中,每个条目对象都位于两个不同的链中:

In the LinkedHashMap implementation, the LinkedHashMap.Entry class extends the HashMap.Entry class, by adding before and after fields. These fields are used to assemble the LinkedHashMap.Entry objects into an independent doubly-linked list that records the insertion order. So, in the LinkedHashMap class, each entry object is in two distinct chains:

  • 有许多通过主哈希数组访问的单链接哈希链.这用于(常规)hashmap 查找.

  • There are a number of singly linked hash chains that is accessed via the main hash array. This is used for (regular) hashmap lookups.

有一个单独的双向链表包含所有条目对象.它以条目插入顺序保存,并在您迭代哈希图中的条目、键或值时使用.

There is a separate doubly linked list that contains all of the entry objects. It is kept in entry insertion order, and is used when you iterate the entries, keys or values in the hashmap.