Set interface of Java container essence

Set interface

The Set interface inherits from Collection. There are no new methods in the Set interface, and the methods remain exactly the same as Collection. Set container features: disordered and non-repeatable .
The commonly used implementation classes of Set are: HashSet, TreeSet, etc. We generally use HashSet.
HashSet
HashSet is implemented using a hash algorithm, and the bottom layer is actually implemented using HashMap (HashSet is essentially a simplified version of HashMap). Therefore, query efficiency and efficiency of addition and deletion are relatively high.
TreeSet The
bottom layer of TreeSet is actually implemented with TreeMap, and a simplified version of TreeMap is maintained internally, which stores Set elements through keys.
The stored elements need to be sorted inside the TreeSet. Therefore, our corresponding class needs to implement the Comparable interface. In this way, the size between objects can be compared according to the compareTo() method, and internal sorting can be performed.

Key points of using TreeSet:

  1. Since it is a binary tree, the elements need to be sorted internally.
    If the class to be placed in the TreeSet does not implement the Comparable interface, an exception will be thrown: java.lang.ClassCastException.
  2. Null elements cannot be placed in the TreeSet.
    Java self-study website

Guess you like

Origin blog.csdn.net/weixin_46083166/article/details/105437695