October 15, 2020 I used TreeSet in Java, but I didn't understand the difference from HashSet, so I record it.
A collection is an object that collects elements. Collection classes are roughly divided into three types: List, Map, and Set. Each is divided into classes with different properties.
There are two types of List structure, ArrayList and LinkedList. The List structure is a structure in which elements are ordered and managed, and since the elements are arranged in the order of index numbers, elements can be acquired, inserted, updated, changed, etc. by specifying the numbers.
There are two types of Map structures, HashMap and TreeMap. The Map structure is a data structure that manages a set of keys and values as one element, and since the elements are managed as keys, you can specify the key and not update or delete the value. The HashSet and TreeSet handled this time have a Set structure as the name implies, and are summarized below.
There are two types of Set structures, HashSet and TreeSet, which are data structures that manage elements without ordering them. Since there is no ordering like List and key management like Map, iterator or extended for statement is used to get the elements. Elements cannot be duplicated </ b> (If the same key is set, it will be overwritten.) The differences between HashMap and TreeSet can be summarized as follows.
--HashMap does not matter the order of acquisition --TreeSet can get elements in sorted order --HashMap can't handle null --TreeSet can handle null
HashMap does not guarantee the order of element acquisition, but TreeSet is automatically sorted and managed, so elements can be acquired in the sorted order. Also, HashMap can use null for elements, but TreeSet can use null.
Not only the Set structure but also the features of the collection class are easily summarized in a table.
ArrayList | LinkedList | HashMap | TreeMap | HashSet | TreeSet | |
---|---|---|---|---|---|---|
interface | List | List | Map | Map | Set | set |
Duplicate elements | 〇 | 〇 | × | × | × | × |
null element | 〇 | 〇 | 〇 | × | × | × |
Automatic sorting | × | × | × | 〇 | 〇 | 〇 |
Although not mentioned above, ArrayList is characterized by fast acquisition and slow insertion and deletion, and LinkedList is characterized by fast element insertion and deletion but slow acquisition.
TreeSet class Comparison of collection classes
Recommended Posts