[Knowledge sorting] Java Collection (2), Knowledge sorting java Collection

Source: Internet
Author: User

[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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.