Set collection (LinkedHashSet collection)

We instruct HashSet to ensure that the elements are unique, and there is no order in storing historical elements, so what should we do to ensure order?

There is a subclass java.util.LinkedHashSet under HashSet, which is a data storage structure that combines a linked list and a hash table.

The API documentation states:

A hash table and linked list implementation of the Set interface with predictable iteration order. The difference between this implementation and HashSet is that the latter maintains a double linked list that runs on all entries. This linked list defines the iteration order, that is, iterates in the order in which the elements are inserted into the set (insertion order). Note that the insertion order is not affected by the elements reinserted in the set. (If s.add(e) is called immediately after s.contains(e) returns true, the element e will be reinserted into set s.)

Simple understanding: the bottom layer is a hash table (array + linked list/red-black tree) + linked list, and a linked list (recording the storage order of the elements) to ensure that the elements are in order.

public static void main(String[] args) { 
    HashSet<String> hashSet = new HashSet<>(); 
    hashSet.add("fff"); 
    hashSet.add("abc"); 
    hashSet.add("abc") ; 
    hashSet.add("ddd"); 
    System.out.println(hashSet); // [abc, ddd, fff] 
    // It can be seen that the deposit order and the withdrawal order are different, and there is no duplication 

    LinkedHashSet<String> set = new LinkedHashSet<>(); 
    set.add("fff"); 
    set.add("abc"); 
    set.add("abc"); 
    set.add("ddd"); 
    System.out.println(set ); // [fff, abc, ddd] 
    // Ordered, no repetitions allowed 
}

 

Guess you like

Origin blog.csdn.net/wardo_l/article/details/114001494