Java中的LinkedHashSet源碼解讀
更新時間:2023年09月04日 09:48:36 作者:伊顰伊笑
這篇文章主要介紹了Java中的LinkedHashSet源碼解讀,LinkedHashSet?是?Java?中的一個集合類,它是?HashSet?的子類,并實現(xiàn)了?Set?接口,與?HashSet?不同的是,LinkedHashSet?保留了元素插入的順序,并且具有?HashSet?的快速查找特性,需要的朋友可以參考下
LinkedHashSet
基本介紹
- LinkedHashSet 是 HashSet 的子類
- LinkedHashSet 底層是一個 LinkedHashMap,底層維護(hù)了一個數(shù)組+雙向鏈表
- LinkedHashSet 根據(jù)元素的 hashCode 值來決定元素的存儲位置,同時使用鏈表維護(hù)元素的次序(圖),這使得元素看起來是以插入順序保存的。
- LinkedHashSet 不允許添重復(fù)元素
說明
- 在 LinkedHastSet 中維護(hù)了一個 hash 表和雙向鏈表(LinkedHashSet 有head和tail)
- 每一個節(jié)點有 pre 和 next 屬性,這樣可以形成雙向鏈表
- 在添加一個元素時,先求hash值,再求索引,確定該元素在hashtable 的位置,然后將添加的元素加入到雙向鏈表(如果已經(jīng)存在,不添加【原則和 hashset 一樣】)
tail.next = newElement//簡單指定 newElement.pre = tail tail = newEelment;
- 這樣的話,我們遍歷 LinkedHashSet 也能確保插入順序和遍歷順序一致
LinkedHashSet 源碼解讀
package collection_; import java.util.LinkedHashSet; import java.util.Set; /** * @Author: Gin * @Description: * @Modified By: Gin * @Date: Created in 11:12 2021/9/22 */ public class LinkedHashSetSource { public static void main(String[] args) { // 分析 LinkedHashSet 的底層機(jī)制 Set set = new LinkedHashSet(); set.add(new String("AAA")); set.add(456); set.add(456); set.add(new Customer("Tom", 1)); set.add(123); set.add("Gin"); System.out.println("set = " + set); // 解讀: // 1. LinkedHashSet 中元素的取出順序和加入順序一致 // 2. LinkedHashSet(HashSet的子類) 底層其實是 LinkedHashMap(HashMap的子類) // 3. LinkedHashSet 底層結(jié)構(gòu)(table數(shù)組 + 雙向鏈表) // 4. 第一次添加數(shù)據(jù),將 table數(shù)組 直接擴(kuò)容至 16 個空間大小 // 5. table數(shù)組的類型為 HashMap$Node[] // 6. table數(shù)組中存放數(shù)據(jù)的結(jié)點類型是 LinkedHashMap$Entry /* LinkedHashMap 的靜態(tài)內(nèi)部類 Entry 繼承自 HashMap 的靜態(tài)內(nèi)部類 Node static class Entry<K,V> extends HashMap.Node<K,V> { Entry<K,V> before, after; // before, after 用來形成雙向鏈表 Entry(int hash, K key, V value, Node<K,V> next) { super(hash, key, value, next); } } */ } } class Customer{ private String name; private int no; public Customer(String name, int no) { this.name = name; this.no = no; } }
到此這篇關(guān)于Java中的LinkedHashSet源碼解讀的文章就介紹到這了,更多相關(guān)LinkedHashSet源碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Mybatis逆向工程實現(xiàn)連接MySQL數(shù)據(jù)庫
本文主要介紹了Mybatis逆向工程實現(xiàn)連接MySQL數(shù)據(jù)庫,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06springboot中不能獲取post請求參數(shù)的解決方法
這篇文章主要介紹了springboot中不能獲取post請求參數(shù)的解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06SpringBoot整合H2數(shù)據(jù)庫的操作方法
H2是一個Java語言編寫的嵌入式數(shù)據(jù)庫,它不受平臺的限制,同時H2提供了一個十分方便的web控制臺,用于操作和管理數(shù)據(jù)庫內(nèi)容,本文介紹SpringBoot整合H2數(shù)據(jù)庫的方法,感興趣的朋友一起看看吧2024-01-01Spring boot集成spring session實現(xiàn)session共享的方法
這篇文章主要介紹了Spring boot集成spring session實現(xiàn)session共享的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-06-06