Characteristics of Map interface implementation class
- Map and Collection exist side by side. Used to save data with mapping relationship: key value
- The key and value in the Map can be data of any reference type and will be encapsulated in the HashMap$Node object
- Duplicate key s in Map are not allowed. The reason is the same as HashSet. The source code has been analyzed earlier
- The value in the Map can be repeated
- The key and value of Map can be null. Note that there can be only one key and multiple values
- String class is often used as the key of Map
- There is a one-way one-to-one relationship between key and value, that is, the corresponding value can always be found through the specified key
- For the key value diagram of Map storing data, a pair of k-v is placed in a Node. Because the Node implements the Entry interface, some books also say that a pair of k-v is an Entry
package collection_; import java.util.HashMap; import java.util.Map; /** * @Author: Gin * @Description: * @Modified By: Gin * @Date: Created in 9:04 2021/9/23 */ public class Map_ { public static void main(String[] args) { // 1. Map and Collection exist side by side. Used to save data with mapping relationship: key value // 2. The key and value in the map can be data of any reference type and will be encapsulated in the HashMap$Node object // 3. Duplicate key s in map are not allowed. The reason is the same as HashSet. The source code has been analyzed earlier // 4. The value in the map can be repeated // 5. The key and value of map can be null. Note that there can be only one key and multiple values // 6. String class is often used as the key of Map // 7. There is a one-way one-to-one relationship between key and value, that is, the corresponding value can always be found through the specified key Map map = new HashMap(); map.put("no1", "Gin"); map.put("no2", "Sherry"); map.put("no2", "Vodka"); map.put("no3", "Gin"); map.put(null, null); map.put(null, "Rum"); map.put("no4", null); map.put("no5", null); map.put(1, "Vermouth"); map.put(new Object(), "Bourbon"); System.out.println(map); // Pass in the key through the get method, and the corresponding value will be returned System.out.println(map.get(1)); } }
Map features 8: source code interpretation
- For the key value diagram of Map storing data, a pair of k-v is placed in a Node. Because the Node implements the Entry interface, some books also say that a pair of k-v is an Entry
package collection_; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * @Author: Gin * @Description: * @Modified By: Gin * @Date: Created in 15:48 2021/9/23 */ public class MapSource_ { public static void main(String[] args) { Map map = new HashMap(); map.put("no1", "Gin"); // k-v map.put("no2", "Sherry"); // k-v /* tab[i] = newNode(hash, key, value, null); Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) { return new Node<>(hash, key, value, next); } Interpretation: 1. k-v Finally, HashMap$Node node = newNode(hash, key, value, null); 2. k-v In order to facilitate the programmer's traversal, an EntrySet collection is also created. The type of elements stored in the collection is Entry, An entry object has k-v, entryset < entry < K, V > >, that is, transient set < map. Entry < K, V > > entryset; 3. Entry The K and V of the object will point to the key and value in the newNode, that is, the data will not be stored in the Entry object 4. In the entrySet, the defined type is Map.Entry, but the HashMap$Node is actually stored 5. This is because HashMap$Node implements the Map.Entry interface: static class node < K, V > implements Map.Entry < K, V > 6. When the HashMap$Node object is stored in the entrySet, it will be convenient for programmers to traverse, because Map.Entry provides two important methods: K getKey(),V getValue() */ Set set = map.entrySet(); System.out.println(set.getClass()); // The running type of set: HashMap$EntrySet. The Entry objects stored in set are one by one for (Object obj : set) { // System.out.println(obj.getClass()); // Run type of each Entry object: HashMap$Node // Get the k-v through the getKey and getValue methods of Map.Entry Map.Entry entry = (Map.Entry)obj; System.out.println(entry.getKey() + " - " + entry.getValue()); // no2 - Sherry // no1 - Gin } // 7. keySet() and values() methods are also provided // It is used to obtain all key s and value s in the map respectively Set set1 = map.keySet(); System.out.println(set1.getClass()); // HashMap$KeySet Collection values = map.values(); System.out.println(values.getClass()); // HashMap$Values } }
Common methods of Map interface
- put: add
- remove: deletes the mapping relationship based on the key
- Get: get value according to key
- size: get the number of elements
- isEmpty: judge whether the number is 0
- Clear: clear
- containsKey: find whether the key exists
package collection_; import java.util.HashMap; import java.util.Map; /** * @Author: Gin * @Description: * @Modified By: Gin * @Date: Created in 16:56 2021/9/23 */ public class MapSource { public static void main(String[] args) { Map map = new HashMap(); map.put("Deng Chao", new Bookkk("",100)); map.put("Deng Chao", "Sun Li"); map.put("Wang Baoqiang", "Ma Rong"); map.put("Song Zhe", "Ma Rong"); map.put("Liu Lingbo", null); map.put(null, "Liu Yifei"); map.put("Lu Han", "Guan Xiaotong"); Object object = map.get("Deng Chao"); System.out.println(object); map.remove("Lu Han"); System.out.println(map); boolean containsKey = map.containsKey(null); System.out.println(containsKey); System.out.println(map.containsValue("Liu Yifei")); System.out.println(map.size()); System.out.println(map.isEmpty()); map.clear(); /* Output results: Sun Li {Deng Chao = Sun Li, Song Zhe = Ma Rong, Liu Lingbo = null, null = Liu Yifei, Wang Baoqiang = Ma Rong} true true 5 false */ } } class Bookkk{ private String name; private int price; public Bookkk() { } public Bookkk(String name, int price) { this.name = name; this.price = price; } }
Traversal of Map
package collection_; import java.util.*; /** * @Author: Gin * @Description: * @Modified By: Gin * @Date: Created in 17:04 2021/9/23 */ public class MapFor { public static void main(String[] args) { Map map = new HashMap(); map.put("Deng Chao", "Sun Li"); map.put("Wang Baoqiang", "Ma Rong"); map.put("Song Zhe", "Ma Rong"); map.put("Liu Lingbo", null); map.put(null, "Liu Yifei"); map.put("Lu Han", "Guan Xiaotong"); // Group 1: first take out all keys, and then take out the corresponding value according to all keys Set keySet = map.keySet(); // 1. Enhance for System.out.println("==== enhance for ===="); for (Object key : keySet) { System.out.println(key + " - " + map.get(key)); } // 2. Iterator System.out.println("==== iterator ===="); Iterator iterator = keySet.iterator(); while (iterator.hasNext()) { Object key = iterator.next(); System.out.println(key + " - " + map.get(key)); } // Group 2: remove all values Collection values = map.values(); // Here you can use the traversal methods used by all collections // 1. Enhance for System.out.println("==== enhance for ===="); for (Object value : values) { System.out.println(value); } // 2. Iterator System.out.println("==== iterator ===="); Iterator iterator1 = values.iterator(); while (iterator1.hasNext()) { Object value = iterator1.next(); System.out.println(value); } // Group 3: get k-v through entrySet // 1. Enhance for System.out.println("==== Third enhancement for k-v method ===="); Set entrySet = map.entrySet(); for (Object entry : entrySet) { // Convert entry to Map.Entry Map.Entry m = (Map.Entry)entry; System.out.println(m.getKey() + " - " + m.getValue()); } // 2. Iterator System.out.println("==== Third iterator k-v method ===="); Iterator iterator2 = entrySet.iterator(); while (iterator2.hasNext()) { Object entry = iterator2.next(); // System.out.println(entry.getClass()); // HashMap$Node // Downward Transformation: because the Node has no corresponding method, it is transformed into an Entry Map.Entry m = (Map.Entry)entry; System.out.println(m.getKey() + " - " + m.getValue()); } } }
practice
Add 3 employee objects using HashMap. It is required to
Key: employee id
Value: employee object
And traverse the employees with salary > 28000 (at least two traversal methods)
Employee category: name, salary, employee id
package collection_; import java.util.*; /** * @Author: Gin * @Description: * @Modified By: Gin * @Date: Created in 18:50 2021/9/23 */ public class MapExercise { public static void main(String[] args) { Map map = new HashMap(); map.put(1, new Emp("Gin", 35600, 1)); map.put(2, new Emp("Vermouth", 40000, 2)); map.put(3, new Emp("Vodka", 28000, 3)); Set keySet = map.keySet(); // Take out all key s and enhance for System.out.println("===The first traversal method==="); for (Object key : keySet) { Emp emp = (Emp) map.get(key); if(emp.getSal() > 28000){ System.out.println(emp); } } // Take out all key s and iterators System.out.println("===The second traversal method==="); Iterator iterator = keySet.iterator(); while (iterator.hasNext()) { Object key = iterator.next(); Emp emp = (Emp) map.get(key); if(emp.getSal() > 28000){ System.out.println(emp); } } // Traversal using the entrySet iterator System.out.println("===The third traversal method==="); Set entrySet = map.entrySet(); Iterator iterator1 = entrySet.iterator(); while (iterator1.hasNext()) { Map.Entry entry = (Map.Entry) iterator1.next(); Emp emp = (Emp) entry.getValue(); if(emp.getSal() > 28000){ System.out.println(emp); } } } } // Employee category: name, salary, employee id class Emp{ private String name; private double sal; private int id; public Emp() { } public Emp(String name, double sal, int id) { this.name = name; this.sal = sal; this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSal() { return sal; } public void setSal(double sal) { this.sal = sal; } public int getId() { return id; } public void setId(int id) { this.id = id; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Emp emp = (Emp) o; return Double.compare(emp.sal, sal) == 0 && id == emp.id && Objects.equals(name, emp.name); } @Override public int hashCode() { return Objects.hash(name, sal, id); } @Override public String toString() { return "Emp{" + "name='" + name + '\'' + ", sal=" + sal + ", id=" + id + '}'; } }
HashMap summary
- Common implementation classes of Map interface: HashMap, Hashtable and Properties.
- HashMap is the most frequently used implementation class of Map interface.
- HashMap stores data in key Val pairs (HashMap$Node type)
- The key cannot be repeated, but the value can be repeated. Null keys and null values are allowed.
- If the same key is added, the original key val will be overwritten, which is equivalent to modification (key will not be replaced, val will be replaced)
- Like HashSet, the mapping order is not guaranteed, because the bottom layer is stored in the form of hash table (jdk8HashMap bottom layer: array + linked list + red black tree)
- HashMap does not achieve synchronization, so it is thread unsafe. The method does not perform synchronization and mutual exclusion, and is not synchronized