集合之LinkedHashSet(含JDK1.8源碼分析)

1、前言

  上篇已經分析了Set接口下HashSet,咱們發現其操做都是基於hashMap的,接下來看LinkedHashSet,其底層實現都是基於linkedHashMap的。html

2、linkedHashSet的數據結構

  由於linkedHashSet的底層是基於linkedHashMap實現的,因此linkedHashSet的數據結構就是linkedHashMap的數據結構,由於前面已經分析過了linkedHashMap的數據結構,這裏再也不贅述。集合之LinkedHashMap(含JDK1.8源碼分析)java

  四個關注點在linkedHashSet上的答案數據結構

3、linkedHashSet源碼分析-屬性及構造函數

  3.1 類的繼承關係less

public class LinkedHashSet<E>
    extends HashSet<E>
    implements Set<E>, Cloneable, java.io.Serializable

  說明:繼承HashSet,實現了Set接口,其內定義了一些共有的操做。函數

  3.2 類的屬性源碼分析

  由上圖可知,除了自己的序列號,linkedHashSet並無定義一些新的屬性,其屬性都是繼承自hashSet。ui

  3.3 類的構造函數this

  說明:如上圖所示,linkedHashSet的四種構造函數都是基於linkedHashMap實現的,這裏列出一種,其它幾種也是同樣。spa

/** * Constructs a new, empty linked hash set with the specified initial * capacity and load factor. * * @param initialCapacity the initial capacity of the linked hash set * @param loadFactor the load factor of the linked hash set * @throws IllegalArgumentException if the initial capacity is less * than zero, or if the load factor is nonpositive */
    public LinkedHashSet(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor, true); }

  經過super調用父類hashSet對應的構造函數,以下:code

/** * Constructs a new, empty linked hash set. (This package private * constructor is only used by LinkedHashSet.) The backing * HashMap instance is a LinkedHashMap with the specified initial * capacity and the specified load factor. * * @param initialCapacity the initial capacity of the hash map * @param loadFactor the load factor of the hash map * @param dummy ignored (distinguishes this * constructor from other int, float constructor.) * @throws IllegalArgumentException if the initial capacity is less * than zero, or if the load factor is nonpositive */ HashSet(int initialCapacity, float loadFactor, boolean dummy) { map = new LinkedHashMap<>(initialCapacity, loadFactor); }

4、linkedHashSet源碼分析-核心函數

  linkedHashSet的add方法,contains方法,remove方法等等都是繼承自hashSet的,也是基於hashMap實現的,只是一些細節上仍是基於linkedHashMap實現而已,前面已經分析過,這裏再也不贅述。

  舉例:

public class Test { public static void main(String[] args) { LinkedHashSet linkedHashSet = new LinkedHashSet<>(); linkedHashSet.add("zs"); linkedHashSet.add("ls"); linkedHashSet.add("ww"); linkedHashSet.add("zl"); linkedHashSet.add(null); linkedHashSet.add("zs"); System.out.println(linkedHashSet); boolean zs1 = linkedHashSet.remove("zs"); System.out.println("刪除zs===" + zs1); System.out.println(linkedHashSet); boolean zs = linkedHashSet.contains("zs"); System.out.println("是否包含zs===" + zs); } }

  結果:可見,linkedHashSet容許空值,不容許重複數據,元素按照插入順序排列。

[zs, ls, ww, zl, null] 刪除zs===true [ls, ww, zl, null] 是否包含zs===false

5、總結

  可見,linkedHashSet是與linkedHashMap相對應的,分析完linkedHashMap再來看linkedHashSet就很簡單了。

相關文章
相關標籤/搜索