1, Map interface description
Store double column data and key value pair data -- similar to functions in high school
- Understanding of Map structure:
Keys in Map: unordered and non repeatable. Use Set to store all keys - > the class where the key belongs is required to override the equals() method and hashCode() method
Value in Map: an unordered and reusable Collection stores all values - > the class where value is located should override the equals() method
A key value pair: key value constitutes an Entry object.
Entries in Map: unordered and non repeatable. Use Set to store all entries
2, Methods defined in Map
2.1 add, delete and modify
- object put(Object key,object value): adds (or modifies) the specified key value to the current map object
public void putTest(){ HashMap map = new HashMap(); //add to map.put("A",'a'); map.put("B",'b'); map.put("C",'c'); map.put("D",'d'); map.put("E",'e'); System.out.println(map); //modify map.put("A","aa"); System.out.println(map); }
output
{A=a, B=b, C=c, D=d, E=e} {A=aa, B=b, C=c, D=d, E=e}
- void putAll(Map m): store all key value pairs in m into the current map
public void test(){ HashMap map = new HashMap(); //add to map.put("A",'a'); map.put("B",'b'); map.put("C",'c'); map.put("D",'d'); map.put("E",'e'); System.out.println(map); HashMap map1 = new HashMap(); map1.putAll(map); System.out.println(map1); }
Output:
{A=a, B=b, C=c, D=d, E=e} {A=a, B=b, C=c, D=d, E=e}
- Object remove(Object key): removes the key value pair of the specified key and returns value
System.out.println(map.remove("A")); System.out.println(map.remove("a")); System.out.println(map);
Output:
aa null {B=b, C=c, D=d, E=e}
- void clear: clear all data in the current map
map.clear(); System.out.println(map); System.out.println(map.size());
Output:
{} 0
2.2 operation of element query:
Object get(Object key): get the value corresponding to the specified key
System.out.println(map.get("D")); System.out.println(map.get("DD"));
d null
boolean containsKey(Object key): whether the specified key is included
System.out.println(map.containsKey("E")); System.out.println(map.containsKey("EE"));
true false
boolean containsValue(Object value): whether the specified value is included
System.out.println(map.containsValue("a")); System.out.println(map.containsValue('a')); System.out.println(map.containsValue("asbha"));
false true false
int size(); Returns the number of key values in the map
System.out.println(map.size());
5
boolean isEmpty(): judge whether the current map is empty
System.out.println(map.isEmpty()); map.clear(); System.out.println(map.isEmpty());
false true
boolean equals(Object obj): judge whether the current map and parameter object obj are equal
HashMap map1 = new HashMap(); //add to map1.put("A",'a'); map1.put("B",'b'); map1.put("C",'c'); map1.put("D",'d'); map1.put("E",'e'); System.out.println(map.equals(map1)); HashMap map2 = new HashMap(); //add to map2.put("A",'a'); map2.put("B",'c'); map2.put("C",'c'); map2.put("D",'d'); map2.put("E",'e'); System.out.println(map.equals(map2));
true false
2.3 meta view operation method:
Set keySet(): returns the Collection set composed of all keys
Collection values(): returns the collection collection composed of all values
Set entrySet(): returns the set set composed of all key value pairs
HashMap map = new HashMap(); //add to map.put("A",'a'); map.put("B",'b'); map.put("C",'c'); map.put("D",'d'); map.put("E",'e'); //ergodic // ``Set keySet() ``: returns the Collection set composed of all keys Set set = map.keySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); } System.out.println("####"); // ``Collection values() ``: returns the collection collection composed of all values Collection values = map.values(); for (Object obj : values){ System.out.println(obj); } System.out.println("####"); // ``Set entrySet() ``: returns the set set composed of all key value pairs Set entrySet = map.entrySet(); Iterator iterator1 = entrySet.iterator(); while (iterator1.hasNext()){ Object obj = iterator1.next(); //All elements in the entry set collection are entries Map.Entry entry = (Map.Entry) obj; System.out.println(entry.getKey() + "--->" + entry.getValue()); }
A B C D E #### a b c d e #### A--->a B--->b C--->c D--->d E--->e
3, Map implementation class
3.1 HashMap
As the main implementation class of Map
HashMap is thread unsafe, but it is efficient
null key or value can be stored
HashMap bottom layer: array + linked list (jdk7 and before), array + linked list + red black tree (jdk8)
3.1.1 LinkedHashMap
Ensure that when traversing Map elements, traversal can be implemented in the order of addition
Reason: Based on the original HashMap underlying structure, a pair of pointers are added to point to the previous and subsequent elements
For frequent traversal operations, this kind of execution efficiency is higher than HashMap
3.2 TreeMap
Ensure that the added key value pairs are sorted to achieve traversal sorting. At this time, consider the natural sorting of keys or customized sorting
Red and black trees are used at the bottom
3.2.1 two ways to add a tree
- Adding key value to TreeMap requires that the key must be an object created by the same class, and one key is the basis for sorting
public void test1(){ TreeMap map = new TreeMap(); map.put("AA", 'a'); map.put(1,'c'); }
Error message:
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
Natural sorting
@Test public void test1(){ TreeMap map = new TreeMap(); User u1 = new User("Tom", 19); User u2 = new User("Alice", 51); User u3 = new User("Bob", 19); User u4 = new User("Jerry", 23); User u5 = new User("Jimi", 25); map.put(u1,98); map.put(u2,45); map.put(u3,65); map.put(u4,18); map.put(u5,54); Set entrySet = map.entrySet(); Iterator iterator1 = entrySet.iterator(); while (iterator1.hasNext()){ Object obj = iterator1.next(); //All elements in the entry set collection are entries Map.Entry entry = (Map.Entry) obj; System.out.println(entry.getKey() + "--->" + entry.getValue()); } }
Output:
User{name='Tom', age=19}--->98 User{name='Jimi', age=25}--->54 User{name='Jerry', age=23}--->18 User{name='Bob', age=19}--->65 User{name='Alice', age=51}--->45
Custom sorting
@Test public void test2(){ TreeMap map = new TreeMap(new Comparator() { @Override public int compare(Object o1, Object o2) { if(o1 instanceof User && o2 instanceof User){ User u1 = (User) o1; User u2 = (User) o2; return Integer.compare(u1.getAge(),u2.getAge()); } throw new RuntimeException("The types entered do not match"); } }); User u1 = new User("Tom", 19); User u2 = new User("Alice", 51); User u3 = new User("Bob", 19); User u4 = new User("Jerry", 23); User u5 = new User("Jimi", 25); map.put(u1,98); map.put(u2,45); map.put(u3,65); map.put(u4,18); map.put(u5,54); Set entrySet = map.entrySet(); Iterator iterator1 = entrySet.iterator(); while (iterator1.hasNext()){ Object obj = iterator1.next(); //All elements in the entry set collection are entries Map.Entry entry = (Map.Entry) obj; System.out.println(entry.getKey() + "--->" + entry.getValue()); } }
Output:
User{name='Tom', age=19}--->65 User{name='Jerry', age=23}--->18 User{name='Jimi', age=25}--->54 User{name='Alice', age=51}--->45
3.3 Hashtable
As an ancient implementation class
Thread safe, but inefficient
Cannot store null key or value
3.3.1 Properties
Commonly used to process configuration files. Both key and value are String types
Application scenario
Configuration file jdbc.properties
name=Tom password=abc123
java file
public static void main(String[] args) { FileInputStream fis = null; try { Properties pros = new Properties(); fis = new FileInputStream("jdbc.properties"); pros.load(fis);//Load corresponding file String name = pros.getProperty("name"); String password = pros.getProperty("password"); System.out.println("name = " + name + ",password = " + password); }catch (IOException e){ e.printStackTrace(); }finally { if(fis != null){ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Output:
name = Tom,password = abc123
# 4, Map related interview questions ## 4.1 underlying implementation principle of HashMap? ### jdk7 ```javascript HashMap map = new HashMap(); //After instantiation, the bottom layer creates a one-dimensional array Entry[] table with a length of 16
map.put(key1,value1); //First, calculate the hashCode of the class where key1 belongs. The method calculates the hash value of key1. After some calculation, the hash value result will be stored in the Entry array //If the data in this location is empty, key1-value1 is added successfully //If the data in this location is not empty, (which means that there are one or more data in this location (in the form of linked list)), compare the hash value of key1 and the existing data: //If the hash value of key1 is different from the hash value of existing data, key1-value1 will be added successfully //How to keep the hash value of key1 the same as that of an existing data (key2-value2) and continue the comparison: call the equals(key2) method of the class where key1 is located to compare: //How to return false: key1-value1 is added successfully //If true is returned: replace value2 with value1 // //
During the continuous addition process, the problem of capacity expansion will be involved. The default capacity expansion method is to double the original capacity and copy the original data
jdk8
- The underlying array of jdk8 is: Node [], not Entry []
- When the put method is called for the first time, the underlying layer creates an array with a length of 16
- The jdk7 underlying structure is only: array + linked list. Underlying structure in jdk8: array + linked list + red black tree
When the number of data stored in the form of a linked list of elements at a redundant position of the array is > 8, and the length of the current array is > 64, all data at this index position will be stored in a red black tree (core modification in jdk8)
new HashMap()//The underlying layer did not create an array with a length of 16