Java collection framework (III)
Map interface
Characteristics of Map implementation class
-
Map: double column data, which stores the data of key value pairs, similar to the function of high school, y=f (x)
-
Implementation class:
-
HashMap: as the main implementation class of Map; Unsafe thread and high efficiency; null key s and value s can be stored
-
When traversing the hashedmap subclass, ensure that the hashedmap subclass can be added according to the traversal order; Because on the basis of 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.
-
TreeMap: ensure to sort according to the added key value pairs and realize sorting traversal. In this case, the natural sorting or customized sorting considering the key is used. Red and black trees are used at the bottom
-
Hashtable: as an ancient implementation class (not commonly used), it is thread safe and inefficient; null key and value cannot be stored
-
Properties: commonly used to process configuration files. key and value are of String type
-
The bottom layer of HashMap: array + linked list (jdk7 before)
Array + linked list + red black tree (jdk8)
-
Understanding of Map structure
- Keys in Map: unordered and non repeatable. Use Set to store all keys - > the class where the key is located should override equals() and hashCode()
- value in Map: unordered and repeatable. Use collection to store all values - > the class where vaule is located should override equals ()
- A key value pair: key value constitutes an Entry object
- Entries in Map: unordered and non repeatable. Set is used to store all entries
Underlying implementation principle of HashMap (taking jdk7 as an example)
- 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, call hashCode () of the class where key1 is located to calculate the hash value of key1. After the hash value is calculated by some algorithm, the storage location in the Entry array is obtained. If the data in this position 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 values of key1 and one or more existing data:
- If the hash value of key1 is different from that of the existing data, key1-vaule1 is added successfully
- If the hash value of key1 is the same as that of an existing data, continue the comparison: call the equals () method of the class where key1 is located, and compare:
- If equals() returns false, key1-value1 is added successfully
- If equals() returns true, replace value2 with value1
- At this time, key1-value1 and the original data are stored in a linked list
- In the process of continuous addition, 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 is different from jdk7 in terms of underlying implementation:
- new HashMap(): the bottom layer does not create an array with a length of 16
- The array at the bottom 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 underlying structure of jdk7 is only array + linked list. The underlying structure of jdk8 is array + linked list + red black tree
- When the number of elements in an index position of the array in the form of linked list is > 8 and the length of the current array is > 64, all data in this index position will be stored in red black tree instead
Underlying implementation principle of LinkedHashMap
-
public void test1(){ Map map=new HashMap(); map.put(123,"AA"); map.put(12,"BB"); map.put(23,"cc"); System.out.println(map);//disorder } @Test public void test2(){ Map map=new LinkedHashMap(); map.put(123,"AA"); map.put(12,"BB"); map.put(23,"cc"); System.out.println(map);//Traverse in addition order }
Common methods of Map interface
- Common method I
public void test3() { Map map = new HashMap(); //add to map.put("AA", 123); map.put("BB", 12); map.put("CC", 23); //modify map.put("AA", 1234); System.out.println(map);//{AA=1234, BB=12, CC=23} Map map1 = new HashMap(); map1.put("GG", 56); map1.put("FF", 567); //2.putAll(Map m): store all key value pairs in m into the current map map.putAll(map1); System.out.println(map);//{AA=1234, BB=12, CC=23, GG=56, FF=567} //3.remove(Object key): removes the key value pair of the specified key and returns value Object gg = map.remove("GG"); System.out.println(map); System.out.println(gg);//56. Remove the value value corresponding to the key } @Test public void test4() { Map map = new HashMap(); map.put("AA", 123); map.put("BB", 12); map.put("CC", 23); //4.get(Object key):h get the value corresponding to the specified key Object bb = map.get("BB"); System.out.println(bb);//12 //5.containsKey(Object key): whether to include the specified key //6.containsValue(Object value): whether to include the specified value boolean aa = map.containsKey("AA"); System.out.println(aa);//true System.out.println(map.containsValue(23));//true //7.int size(): returns the number of key value pairs in the map System.out.println(map.size());//3 //8.isEmpty(): judge whether the current map is empty //9.equals(Object obj): judge whether the current map and parameter object obj are equal Map map1 = new HashMap(); map1.put("GG", 56); map1.put("FF", 567); boolean equals = map.equals(map1); System.out.println(equals);//false }
- Traversal operation
ublic void test5(){ Map map = new HashMap(); map.put("AA", 123); map.put("BB", 12); map.put("CC", 23); //1. Traverse all key sets: keySet() Set set=map.keySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); }//AA BB CC //Traverse all value sets: values() Collection values=map.values(); for (Object obj:values ) { System.out.println(obj); }//123 12 23 //Traverse all key value: entrySet() Set entrySet = map.entrySet(); Iterator iterator1 = entrySet.iterator(); while (iterator1.hasNext()){ System.out.println(iterator1.next()); }//AA=123 BB=12 CC=23 }
How to add TreeMap
- Adding a key value to the TreeMap requires that the key must be an object created by the same class, because it needs to be sorted according to the key: natural sorting and customized sorting
Properties processing properties file
- It is commonly used to process configuration files. key and value are of String type
Collections utility class
- Collections is a tool class that operates on collections such as Set, List and map (it is a tool class that operates on collection and map)
- Collections provides a series of static methods to sort, query and modify collection elements. It also provides methods to set immutable collection objects and realize synchronous control of collection objects
- What is the difference between Collections and Collections?
- One is the interface and the other is the tool class
- Common method test
public void test1(){ List list=new ArrayList(); list.add(123); list.add(45); list.add(0); list.add(-87); System.out.println(list); //1.reverse: reverse Collections.reverse(list); System.out.println(list); //2.shuffle(List): randomly sort the elements of the list set Collections.shuffle(list); System.out.println(list); //3.sort(list): sort the elements of the specified List set in ascending order according to the natural order of the elements //4.swap(List,int i,int j): exchange the elements at I and j in the specified List set } @Test public void test2(){ List list=new ArrayList(); list.add(123); list.add(45); list.add(0); list.add(-87); //5.Object max (Collection): returns the largest element in a given set according to the natural order of elements //6.Object min(Collection): returns the smallest element Comparable max = Collections.max(list); System.out.println(max);//123 //7.int frequency(Collection,Object): returns the number of occurrences of the specified element in the specified collection int frequency = Collections.frequency(list, 45); System.out.println(frequency);//1 //8.void copy (List dest,List src): copy the contents of src to dest // List dest=new ArrayList(); //Collections.copy(dest,list); Wrong writing, DeST space is not enough //System.out.println(dest); List dest= Arrays.asList(new Object[list.size()]); System.out.println(dest.size());//4 Collections.copy(dest,list); System.out.println(dest);//[123, 45, 0, -87] }