Java collection tool Map & Set

1. Concept

Mapand Setis a data structure specially used for searching, and the efficiency of its search is related to its specific instantiation subclass. They define two different data structures and characteristics respectively:

  1. Map:Map is a collection of key-value pairs, each key-value pair is an element.
  2. Set:Set is a collection that does not allow duplicate elements (keys).


By looking at the Java collection framework diagram, you can see that,The Set interface has two implementation classes: TreeSet class and HashSet classThe Map interface has two implementation classes: TreeMap and HashMap

2. Map

Map is an interface class,Not inherited from Collection, what is stored in this interface class is <K,V>the key-value pair of the structure, and K must be unique and cannot be repeated.

Map common methods

method describe
V get(Object key) Returns the value corresponding to the key
V getOrDefault(Object key, V defaultValue) Returns the value corresponding to the key, or the default value if the key does not exist
V put(K key, V value) Set the value corresponding to the key
V remove(Object key) Delete keys and their corresponding mapping relationships
int size() Returns Mapthe number of key-value pairs
Set keySet() Returns a unique set of all keys
Collection values() Returns a repeatable collection of all values
Set<Map.Entry<K, V>> entrySet() Returns a collection of all key-value mappings
boolean containsKey(Object key) Determine whether the specified key is included
boolean containsValue(Object value) Determine whether the specified value is contained

In the above Map method, a special type appears in the return value of the entrySet() method Map.Entry<K, V>. It is an internal interface implemented internally by Map to store the <key, value> key-value pair mapping relationship. This internal interface mainly provides Methods for obtaining key and value, as well as setting value:

method describe
K getKey() Returns the key in entry
V getValue() Return the value in entry
V setValue(V value) Replace the value in a key-value pair with the specified value

Notice:

  1. Map is an interface and cannot directly instantiate objects. If you want to instantiate an object, you can only instantiate its implementation class TreeMap or HashMap. There is also a LinkedHashMap. LinkedHashMap maintains a doubly linked list based on HashMap to record the insertion order of elements. .
  2. The Key that stores key-value pairs in the Map is unique, and the value can be repeated.
  3. When inserting a key-value pair into a TreeMap, the key cannot be empty, otherwise a NullPointerException will be thrown, and the value can be empty. But
    both the key and value of HashMap can be empty.
  4. All Keys in Map can be separated and stored in Set for access (because Key cannot be repeated).
  5. The values ​​in the Map can all be separated and stored in any sub-collection of the Collection (values ​​may be duplicated).
  6. The Key of the key-value pair in the Map cannot be modified directly, but the value can be modified. If you want to modify the key, you can only delete the key first and then reinsert it
    .

The difference between TreeMap and HashMap

Attributes TreeMap HashMap
underlying data structure red black tree hash bucket
Insertion/deletion/search time complexity O(log N) O(1)
Is it in order? About Key order disorder
thread safety not safe not safe
Insert/delete/find differences Element comparison is required Calculate hash address through hash function
Compare and overwrite The key must be comparable, otherwise ClassCastExceptionan exception will be thrown Custom types need to override equalsand hashCodemethods
Application scenarios In scenarios where Key ordering is required It doesn’t matter whether the Key is in order or not, it requires higher time performance.

3. Set

In Java collection classes, there are two main differences between Set and Map:Set is an interface class inherited from Collection, only Key is stored in Set.

Set common methods

method describe
boolean add(E e) Add elements, but duplicate elements will not be added successfully
void clear() Clear collection
boolean contains(Object o) Determine owhether it is in the set
Iterator iterator() Return iterator
boolean remove(Object o) Delete from the collectiono
int size() Returns the number of elements in the set
boolean isEmpty() Check whether the set is empty, return if empty true, otherwise returnfalse
Object[] toArray() Convert elements in set to array and return
boolean containsAll(Collection<?> c) cWhether all the elements in the set exist in the set, it is returned true, otherwise it is returnedfalse
boolean addAll(Collection<? extends E> c) Adding cthe elements in the set to the set can achieve the effect of deduplication

Notice:

  1. Set is an interface class inherited from Collection
  2. Only the key is stored in the Set, and the key must be unique.
  3. The bottom layer of TreeSet is implemented using Map, which uses a default object of key and Object as a key-value pair to be inserted into the Map.
  4. The biggest function of Set is to deduplicate the elements in the set
  5. 实现Set接口的常用类有TreeSet和HashSet,还有一个LinkedHashSet,LinkedHashSet是在HashSet的基础
    上维护了一个双向链表来记录元素的插入次序。
  6. Set中的Key不能修改,如果要修改,先将原来的删除掉,然后再重新插入
  7. TreeSet中不能插入null的key,HashSet可以。

TreeSet和HashSet的区别

Set底层结构 TreeSet HashSet
底层结构 红黑树 哈希桶
插入/删除/查找时间复杂度 O(log N) O(1)
是否有序 关于Key有序 不一定有序
线程安全性 不安全 不安全
插入/删除/查找区别 按照红黑树的特性来进行插入和删除 先计算key哈希地址,然后进行插入和删除
比较与覆写 key必须能够比较,否则会抛出ClassCastException异常; 自定义类型需要覆写equals和hashCode方法
应用场景 需要Key有序场景下 Key是否有序不关心,需要更高的时间性能

下期预告

上述提到了HashMap 和 HashSet,它们底层都使用到了哈希表结构,关于 哈希表,我们下一章节介绍!

Guess you like

Origin blog.csdn.net/LEE180501/article/details/132031762