集合之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就很简单了。

相关文章
相关标签/搜索