Java - LinkedHashSet 源码阅读笔记

in TCEH Java

简介

LinkedHashSet提供带顺序的HashSet。直接继承HashSet,并实现Set接口。其核心是由HashSet提供的特定构造方法使用LinkedHashMap来存储数据。增删改查全由HashSet控制,更确切说是LinkedHashMap控制。遍历顺序:先进先出。

LinkedHashSet 类

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);
    }
    @Override
    public Spliterator<E> spliterator() {
        return Spliterators.spliterator(this, Spliterator.DISTINCT | Spliterator.ORDERED);
    }

HashSet 构造方法

    HashSet(int initialCapacity, float loadFactor, boolean dummy) {
        // 使用LinkedHashMap来存储数据。遍历时默认插入顺序,也就是先进先出
        map = new LinkedHashMap<>(initialCapacity, loadFactor);
    }