[Knowledge sorting] Java Collection (2), Knowledge sorting java Collection
I. Several Classes for implementing Set
HashSet, javashashset, TreeSet, ConcurrentSkipListSet, CopyOnWriterArraySet
2. Underlying data structure
HashSet-hash table
LinkedHashSet-hash table and linked list
TreeSet-red/black tree
ConcurrentSkipListSet-jump table
CopyOnWriteArraySet-array list
Iii. application scenarios
Here, we will first explain the sequence in which the elements are sorted and applied for the Set selection. Finally, we will discuss the Set selection from the thread security perspective.
1. Order or not
HashSet:
If there is no sequence requirement for the Set insertion, HashSet is recommended. HashSet is actually an instance that uses HashMap (the key value is an element, and value is a meaningless object, and HashMap will be detailed later in the chapter ). At the underlying layer of a HashSet, Hash is used to store element hashes in different places (Zipper mode ).
If order is required, we need to consider hashset and TreeSet.
2. In what order do we save the Set elements?
Based on HashSet, LinkedHashSet uses a double-stranded table to record the insertion sequence.
TreeSet uses the tree structure (red-black tree algorithm), that is, TreeSet can customize the sorting rules of elements in the Set.
3. thread security?
The Set provides two thread-safe classes: ConcurrentSkipListSet and CopyOnWriteArraySet.
CopyOnWriteArraySet adopts read/write splitting and retains "snapshots" as mentioned in the previous article. Therefore, the traversal operation is highly efficient and will not conflict with other threads.
ConcurrentSkipListSet adopts the data structure of the table to ensure that the contains, add, and remove operations are atomic and safe in a multi-threaded environment, however, batch operations such as addAll, removeAll, and containsAll cannot be secured in a multi-threaded environment.