集合之LinkedHashSet(含JDK1.8源碼分析)
一、前言
上篇已經分析了Set接口下HashSet,我們發現其操作都是基於hashMap的,接下來看LinkedHashSet,其底層實現都是基於linkedHashMap的。
二、linkedHashSet的數據結構
因為linkedHashSet的底層是基於linkedHashMap實現的,所以linkedHashSet的數據結構就是linkedHashMap的數據結構,因為前面已經分析過了linkedHashMap的數據結構,這裏不再贅述。集合之LinkedHashMap(含JDK1.8源碼分析)。
四個關註點在linkedHashSet上的答案
三、linkedHashSet源碼分析-屬性及構造函數
3.1 類的繼承關系
public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable, java.io.Serializable
說明:繼承HashSet,實現了Set接口,其內定義了一些共有的操作。
3.2 類的屬性
由上圖可知,除了本身的序列號,linkedHashSet並沒有定義一些新的屬性,其屬性都是繼承自hashSet。
3.3 類的構造函數
說明:如上圖所示,linkedHashSet的四種構造函數都是基於linkedHashMap實現的,這裏列出一種,其它幾種也是一樣。
/** * 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對應的構造函數,如下:
/** * 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); }
四、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
五、總結
可見,linkedHashSet是與linkedHashMap相對應的,分析完linkedHashMap再來看linkedHashSet就很簡單了。
集合之LinkedHashSet(含JDK1.8源碼分析)