LinkedHashSet source code analysis

 LinkedHashSet has the query speed of HashSet, and internally uses a linked list to maintain the order of elements (the order of insertion). So when using the iterator to traverse the Set, the results are displayed in the order in which the elements were inserted.

See the contents of 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);
    }
}

LinkedHashSet inherits from HashSet, and HashSet is implemented based on HashMap. Looking at the LinkedHashSet class, it only defines four construction methods, and I haven't seen the content related to the linked list. Why do you say that LinkedHashSet uses a linked list to maintain the insertion order of elements (insertion order)?

Note that the constructors here all call the fifth constructor of the parent class HashSet: HashSet(int initialCapacity, float loadFactor, boolean dummy). If you still remember the above content, you should understand why it is based on linked list. The content of this construction method is given below.

HashSet(int initialCapacity, float loadFactor, boolean dummy) {
     map = new LinkedHashMap<E,Object>(initialCapacity, loadFactor);
 }

What this method creates is a LinkedHashMap. LinkedHashMap inherits from HashMap, and has a linked list structure to maintain the order of elements. By default, elements are inserted (see "LinkedHashMap Source Code Analysis" ), so LinkedHashSet has the access speed of HashSet (because the access is done through HashSet. method access), while maintaining order.

Summary: The constructor of LinkedHashSet calls the constructor of the parent class HashSet, the constructor of Hashset calls LinkedHashMap, LinkedHashMap inherits from HashMap, and there is a linked list to maintain the order of elements. This is how linked lists come about. LinkedHashSet--HashSet--Create a LinkedHashMap

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324849913&siteId=291194637