欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java中的LinkedHashSet集合解讀

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

LinkedHashSet介紹

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

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

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

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

構(gòu)造方法

LinkedHashSet()

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

LinkedHashSet(int initialCapacity, float loadFactor)

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

關(guān)鍵方法

public boolean add(E e)

說明:向集合中添加元素

public boolean remove(Object o)

說明:向集合中刪除元素

public void clear()

說明:清空集合元素

public int size()

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

使用案例

驗(yàn)證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é)果:

驗(yàn)證LinkedHashSet存儲(chǔ)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底層是一個(gè) LinkedHashMap,底層維護(hù)了一個(gè)數(shù)組+雙向鏈表。

它根據(jù)元素的hashCode值來決定元素的存儲(chǔ)位置,同時(shí)使用鏈表維護(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è)構(gòu)造函數(shù),基本上都是調(diào)用父類HashSet的構(gòu)造函數(shù)。

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

總結(jié)

LinkedHashSet主要適用于對(duì)于元素的添加順序讀取有要求的場(chǎng)景,比如FIFO這樣的場(chǎng)景。

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

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

相關(guān)文章

最新評(píng)論