This article recommends that after understandingHash tableandbinary search treeIt is better to eat after .
Link: Binary Search Tree and Hash Table (JAVA)
Map and Set are both containers or data structures specially used for searching. The efficiency of their search is related to their specific instantiated subclasses.
Map interface
- 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;
Map<Integer,Integer> map1 = new HashMap<>();
Map<Integer,Integer> map2 = new TreeMap<>();
The Map interface does not inherit Collection. This class stores key-value pairs of the <K,V> structure, andK is unique and cannot be repeated. Value can Repeat.
The data in Map is stored in Key-Value model .
Generally searched data is called Key, and its value is Become Value.
For example: using the Key-Value model to count the number of word occurrences can be stored as: <word, number of word occurrences>.
Some common methods in Map:
put(key, value)
If the Key does not exist, insert the current key-value pair. If the current Key exists, update the value corresponding to the key.
Map<String,Integer> map = new TreeMap<>();
map.put("zhangsan", 5);
System.out.println(map);
Map<String,Integer> map = new TreeMap<>();
map.put("zhangsan", 5);
map.put("zhangsan", 10);
System.out.println(map);
get(Key)
Returns the value corresponding to key; if there is no corresponding Key, returns null.
Map<String,Integer> map = new TreeMap<>();
map.put("zhangsan", 5);
System.out.println(map.get("zhangsan"));
Map<String,Integer> map = new TreeMap<>();
map.put("zhangsan", 5);
System.out.println(map.get("zll"));
getOrDefault(key, defaultValue)
Return the value corresponding to key. If key does not exist, return defaultValue.
Map<String,Integer> map = new TreeMap<>();
map.put("zhangsan", 5);
System.out.println(map.getOrDefault("zhangsan", 0));
System.out.println(map.getOrDefault("llll", 0));
remove(key)
Delete the mapping relationship corresponding to key (delete Key and its corresponding Value), and return Value. If the current key does not exist, return null.
Map<String,Integer> map = new TreeMap<>();
map.put("zhangsan", 5);
map.put("lisi", 5);
map.put("wangwu", 5);
System.out.println(map);
//删除“zhangsan”返回5
System.out.println(map.remove("zhangsan"));
//因为不存在“zhangsan”返回null
System.out.println(map.remove("zhangsan"));
System.out.println(map);
void clear()
Delete all key-value pairs in the collection
Map<String,String> map = new TreeMap<>();
map.put("sd","sd");
System.out.println(map);
map.clear();
System.out.println(map);
size()
Returns the number of key-value pairs in the map.
Map<String,String> map = new TreeMap<>();
map.put("sd","sd");
System.out.println(map.size());
Set < K > keySet()
Returns a collection object containing all keys.
The return value of this method is a collection of Set type, which contains all key keywords in the current class (Duplicate values cannot be stored in Set< /span>).
Map<String,Integer> map = new TreeMap<>();
map.put("zhangsan", 5);
map.put("lisi", 5);
map.put("wangwu", 5);
System.out.println(map);
Set<String> tmp = map.keySet();
System.out.println(tmp);
boolean isEmpty()
Determine whether the current map collection is empty.
Returns true if empty; otherwise returns false.
Map<String,String> map = new TreeMap<>();
System.out.println(map.isEmpty());
map.put("sd","sd");
System.out.println(map.isEmpty());
Collection< V > values()
Returns a repeatable collection of all values.
Similar to the keySet() method above, this method returns a collection of Values.
Map<String,Integer> map = new TreeMap<>();
map.put("zhangsan", 5);
map.put("lisi", 5);
map.put("wangwu", 5);
System.out.println(map);
Collection<Integer> tmp = map.values();
System.out.println(tmp);
containsKey(key)
Determine whether the key is included. The return type is boolean.
containsValue(value)
Determine whether the value is included. The return type is boolean.
Set<Map.Entry<K, V>> entrySet()
Returns all key-value mapping relationships.
Before understanding this method, first understand Map.Entry<K, V> .
Map.Entry<K, V>
Map can actually be imagined as a linked list. Each key-value pair in it is stored in the form of a node.Map.Entry<K, V> ; is the internal class implemented inside Map to store the <key, value> key-value pair mapping relationship.
In Map.Entry<K, V>, it mainly provides the : setting and Key comparison method, valueGet
- getKey(): returns the key in entry
- getValue(): returns the value in entry
- setValue(V value): Replace the value in the key-value pair with the specified value
Let’s look at the entrySet() method at this time:
The entrySet() method actually returns all the nodes in the map collection and then treats them as a The whole is stored in a collection of Set type.
Map<String,Integer> map = new TreeMap<>();
map.put("zhangsan", 5);
map.put("lisi", 5);
map.put("wangwu", 5);
Set<Map.Entry<String,Integer>> tmp = map.entrySet();
//第一种遍历方式
System.out.println(tmp);
System.out.println("===========");
//第二种遍历方式
for (Map.Entry<String,Integer> a:map.entrySet()) {
System.out.println("Key:"+a.getKey()+" "+"Value"+a.getValue());
}
Some notes on Map
- Map is an interface and cannot instantiate objects directly. If you want to instantiate an object, you can only instantiate its implementation class TreeMap or HashMap;
- Key-value pairs are stored in MapKey is unique and value can be repeated;
- When inserting key-value pairs inTreeMap, key cannot be empty< a i=4>, otherwise NullPointerException will be thrown, value can be empty. ButHashMap’s key and value can be empty;
- The key-value pair in the MapKey cannot be modified directly, but the value can be modified. If you want to modify the key, you can only delete the key first. remove it and then reinsert it.
The difference between TreeMap and HashMap:
TreeMap | HashMap | |
---|---|---|
underlying structure | red black tree | hash bucket |
Insert/delete/find time | O(log2N) | 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 | key must be comparable, otherwise a ClassCastException will be thrown | Custom typeNeed to override equals and hashCode methods |
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. |
Set interface
Set is much simpler than Map.
- Set is an interface and cannot directly instantiate objects. If you want to instantiate an object you can only instantiate its implementation class TreeSet or HashSet.
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new TreeSet<>();
There are two main differences between Set and Map: Set is an interface class inherited from Collection, and only Key is stored in Set.
Some common methods in Set:
boolean add(Object o)
Add element
Returns true if the addition is successful; returns false if it fails.
Set<String> set = new TreeSet<>();
System.out.println(set.add("asd"));
//因为该元素已经存在了,所以不会添加成功,返回false
System.out.println(set.add("asd"));
boolean addAll(Collection<? extendsE>c)
Adding elements in set c to set can achieve the effect of deduplication.
void clear()
Clear collection
Set<String> set = new TreeSet<>();
set.add("a");
set.add("s");
set.add("d");
set.add("g");
System.out.println(set);
//删除所有元素
set.clear();
System.out.println(set);
boolean contains(Object o)
Determine whether o is in the set
Set<String> set = new TreeSet<>();
set.add("a");
set.add("s");
set.add("d");
set.add("g");
System.out.println(set.contains("s"));
System.out.println(set.contains("hhh"));
Iterator iterator()
Returns an iterator
Set<String> set = new TreeSet<>();
set.add("a");
set.add("s");
set.add("d");
set.add("g");
//利用迭代器进行集合的遍历
Iterator<String> tmp = set.iterator();
while (tmp.hasNext()) {
System.out.print(tmp.next()+" ");
}
boolean remove(Object o)
Delete o in the collection
Returns true if the deletion is successful; false if it fails.
Set<String> set = new TreeSet<>();
set.add("a");
set.add("s");
set.add("d");
set.add("g");
System.out.println(set.remove("a"));
//因为集合中不存在“asd”所以删除失败,返回false
System.out.println(set.remove("asd"));
int size()
Returns the number of elements in the set collection
Set<String> set = new TreeSet<>();
set.add("a");
set.add("s");
set.add("d");
set.add("g");
System.out.println(set.size());
boolean isEmpty()
Check whether the set is empty, return true if empty, otherwise return false
Set<String> set = new TreeSet<>();
System.out.println(set.isEmpty());
set.add("a");
set.add("s");
System.out.println(set.isEmpty());
Object[] toArray()
Convert elements in set to array and return
Set<String> set = new TreeSet<>();
set.add("a");
set.add("s");
Object[] tmp =set.toArray();
for (int i = 0; i < 2; i++) {
System.out.println(tmp[i]);
}
Set<String> set = new TreeSet<>();
set.add("a");
set.add("s");
//此处不能进行强制类型转换
String[] tmp =(String[]) set.toArray();
System.out.println(tmp);
boolean containsAll(Collection<?> c)
Returns true if all the elements in set c exist in set, otherwise returns false
Some notes on Set
- Set is an interface class inherited from Collection;
- Set only stores key, and requires that key must be unique< a i=4>;
- 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;
- The biggest function of Set is to deduplicate elements in the set;
- Common classes that implement the Set interface include TreeSet and HashSet, and there is also a LinkedHashSet. LinkedHashSet maintains a doubly linked list based on HashSet to record the insertion order of elements;
- The Key in Set cannot be modified. If you want to modify it, delete the original one first and then reinsert it
- TreeSet cannot insert null keys, but HashSet can.
The difference between TreeSet and HashSet:
TreeSet | HashSet | |
---|---|---|
underlying structure | red black tree | hash bucket |
Insert/delete/find time | O(log2N) | O(1) |
Is it in order? | About Key order | Not necessarily in order |
Thread safety | not safe | not safe |
Insert/delete/find differences | Insert and delete according to the characteristics of red-black tree | First calculate the key hash address and then insert and delete |
Compare and overwrite | key must be comparable, otherwise a ClassCastException will be thrown | Custom typeNeed to override equals and hashCode methods |
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. |