亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Java中的LinkedHashSet集合解讀

 更新時間:2023年09月04日 11:20:20   作者:C陳三歲  
這篇文章主要介紹了Java中的LinkedHashSet集合解讀,LInkedHashSet這個容器不知道大家在平時的工作用的多嗎,反正我基本上沒有用過,所以,本文主要對于它的特點(diǎn)、使用場景、實(shí)現(xiàn)原理,做一個講解,希望對大家平時的工作有所幫助,需要的朋友可以參考下

LinkedHashSet介紹

LinkedHashSet是一個基于LinkedHashMap實(shí)現(xiàn)的有序去重集合列表。

  • LinkedHashSet中的元素沒有重復(fù)
  • LinkedHashSet中的元素有順序,維護(hù)了添加順序
  • LInkedHashSet可以存儲null值
  • LinkedHashSet是一個線程不安全的容器

以上是LinkedHashSet的類結(jié)構(gòu)圖:

  • 繼承了HashSet,所以它是在HashSet的基礎(chǔ)上維護(hù)了元素添加順序的功能

構(gòu)造方法

LinkedHashSet()

說明: 創(chuàng)建一個空的容器列表,默認(rèn)的初始容量為16,負(fù)載因子為0.75

LinkedHashSet(int initialCapacity, float loadFactor)

說明:創(chuàng)建一個指定初始容量和負(fù)載因子的容器

關(guān)鍵方法

public boolean add(E e)

說明:向集合中添加元素

public boolean remove(Object o)

說明:向集合中刪除元素

public void clear()

說明:清空集合元素

public int size()

說明:返回集合中元素的數(shù)量

使用案例

驗證LinkedHashSet的順序性

@Test
    public void test1() {
        Set<Integer> set = new LinkedHashSet<>();
        set.add(5);
        set.add(4);
        set.add(5);
        set.add(3);
        set.add(1);
        set.add(9);
        //正順序遍歷
        System.out.print("遍歷:");
        set.forEach(item -> {
            System.out.print(item + "  ");
        });
    }

運(yùn)行結(jié)果:

驗證LinkedHashSet存儲null值

@Test
    public void test2() {
        Set<Integer> set = new LinkedHashSet<>();
        set.add(null);
        set.add(5);
        System.out.println(set);
    }

運(yùn)行結(jié)果:

核心機(jī)制

底層有序性實(shí)現(xiàn)機(jī)制

LinkedHashSet底層是一個 LinkedHashMap,底層維護(hù)了一個數(shù)組+雙向鏈表。

它根據(jù)元素的hashCode值來決定元素的存儲位置,同時使用鏈表維護(hù)元素的次序, 這使得元素看起來是以插入順序保存的。

源碼解析

本文主要從源碼角度看下LinkedhashSet確實(shí)是依賴于LinkedHashMap,具體的邏輯還是要關(guān)注LinkedHashMap的實(shí)現(xiàn)。

public class LinkedHashSet<E>
    extends HashSet<E>
    implements Set<E>, Cloneable, java.io.Serializable {
    public LinkedHashSet(int initialCapacity, float loadFactor) {
        super(initialCapacity, loadFactor, true);
    }
    public LinkedHashSet(int initialCapacity) {
        super(initialCapacity, .75f, true);
    }
    public LinkedHashSet() {
        super(16, .75f, true);
    }
    public LinkedHashSet(Collection<? extends E> c) {
        super(Math.max(2*c.size(), 11), .75f, true);
        addAll(c);
    }
}

LinkedHashSet繼承于HashSet,它的源碼很少,只有幾個構(gòu)造函數(shù),基本上都是調(diào)用父類HashSet的構(gòu)造函數(shù)。

查看父類的構(gòu)造函數(shù),它是一個非public的構(gòu)造函數(shù),創(chuàng)建了一個LinkedHashMap, 所以說是依賴于LinkedHashMap實(shí)現(xiàn)的。

總結(jié)

LinkedHashSet主要適用于對于元素的添加順序讀取有要求的場景,比如FIFO這樣的場景。

至于性能方面,大家也不用太過于擔(dān)心,LinkedHashSet插入性能略低于HashSet,但在迭代訪問set里面的全部元素時有很好的性能。

到此這篇關(guān)于Java中的LinkedHashSet集合解讀的文章就介紹到這了,更多相關(guān)Java的LinkedHashSet內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論