1. Map interface
1.1 Overview of Map Interface
By looking at the description of the Map interface, we find that the collection under the Map interface is different from the collection under the Collection interface. They store data in different forms, as shown in the following figure.
In collections, elements exist in isolation (understood as singletons), and they are stored one by one in a Collection.
The set of elements in a Map exists in pairs (understood as husband and wife). Each element consists of a key and a value, through which the corresponding value can be found.
The set in Collection is called a single column set, and the set in Map is called a double column set.
It should be noted that the set in Map cannot contain duplicate keys, and the values can be duplicated; each key can only correspond to one value.
Common sets in Map are HashMap set and LinkedHashMap set.
1.2 Overview of Common Collections in Map Interfaces
By looking at the description of Map interface, we can see that Map has many subclasses. Here we mainly discuss the commonly used HashMap collection and LinkedHashMap collection.
HashMap < K, V>: The hash table structure used to store data, the access order of elements can not guarantee consistency. To ensure that the keys are unique and not duplicated, the hashCode() method and equals() method of the keys need to be rewritten.
LinkedHashMap < K, V>: There is a subclass LinkedHashMap under the HashMap. The hash table structure + linked list structure is used to store data. The access order of elements can be guaranteed by the linked list structure; the unique and non-repetitive keys can be guaranteed by the hash table structure, rewriting the hashCode() method and equals() method of keys.
Note: The set in the Map interface has two generic variables < K, V>, and when used, the data type should be assigned to the two generic variables. The data types of the two generic variables < K, V> can be the same or different.
1.3 Common Methods in Map Interface
put method: Corresponds the specified key to the value and adds it to the collection
Method return value is the value corresponding to the key
When using the put method, if the specified key is not in the collection, then there is no corresponding value of the key, return null, and add the specified key value to the collection;
When using the put method, if the specified key exists in the set, the return value is the value corresponding to the key in the set (the value before replacement), and the value corresponding to the specified key is replaced with the specified new value.
get method: get the value corresponding to the specified key
remove method: remove the element according to the specified key and return the value of the deleted element.
Demonstration of Map Interface Method
public class MapDemo { public static void main(String[] args) { //Establish Map object Map<String, String> map = new HashMap<String,String>(); //to map Adding elements to map.put("Monday", "Monday"); map.put("Sunday", "Sunday"); System.out.println(map); // {Sunday=Sunday, Monday=Monday} //When given Map Adding an element to it returns key Corresponding to the original value Value, if key No corresponding value, return null System.out.println(map.put("Monday", "Mon")); // Monday System.out.println(map); // {Sunday=Sunday, Monday=Mon} //According to the specified key Get the corresponding value String en = map.get("Sunday"); System.out.println(en); // Sunday //according to key Delete elements,Will return key Corresponding value value String value = map.remove("Sunday"); System.out.println(value); // Sunday System.out.println(map); // {Monday=Mon} } }
1.4 Map Set Traversal Key Value Finding Method
Key Value Finding: Get the corresponding value of the key through the key in the element
Operation steps and illustrations:
1. Get all the keys in the Map collection, and since the keys are unique, return a Set collection to store all keys.
2. Traverse the Set of Set keys to get each key
3. Get the corresponding value of the key according to the key
Code demonstration:
public class MapDemo { public static void main(String[] args) { //Establish Map object Map<String, String> map = new HashMap<String,String>(); //to map Adding elements to map.put("Deng Chao", "Sun Li"); map.put("Li Chen", "Fan Bingbing"); map.put("Lau Andy", "Liu Yan"); //Obtain Map All of them key Set<String> keySet = map.keySet(); //Traverse to store all key Of Set aggregate Iterator<String> it =keySet.iterator(); while(it.hasNext()){ //Get each key String key = it.next(); //adopt key Get the corresponding value String value = map.get(key); System.out.println(key+"="+value); } } }
1.5 Entry key-value pair object
In Map class design, a nested interface is provided: Entry. Entry encapsulates the corresponding relationships of key-value pairs into objects. That is, the key-value pair object, so that when we traverse the Map collection, we can get the corresponding key and value from each key-value pair (Entry) object.
Entry is a static internal nested interface provided in Map interface.
getKey() method: Gets the key in the Entry object
getValue() method: Gets the value in the Entry object
entrySet() method: Used to return all key-value pair (Entry) objects in the Map collection, returned in the form of Set collection.
1.6 Map Set Traversal Key Value Pairs
Key-value pairing: Get the key and value in the key-value pair (Entry) object through each key-value pair (Entry) object in the set.
Operation steps and illustrations:
1. Get all the key-value pairs (Entry) objects in the Map collection and return them as Set sets.
2. Traverse the Set set containing key-value pairs (Entry) objects and get each key-value pair (Entry) object.
3. Get the key and value in Entry object by using the key-value pair (Entry) object.
public class MapDemo { public static void main(String[] args) { //Establish Map object Map<String, String> map = new HashMap<String,String>(); //to map Adding elements to map.put("Deng Chao", "Sun Li"); map.put("Li Chen", "Fan Bingbing"); map.put("Lau Andy", "Liu Yan"); //Obtain Map All of them key And value Corresponding relationship Set<Map.Entry<String,String>> entrySet = map.entrySet(); //ergodic Set aggregate Iterator<Map.Entry<String,String>> it =entrySet.iterator(); while(it.hasNext()){ //Get each pair of correspondences Map.Entry<String,String> entry = it.next(); //Get the corresponding by each pair of corresponding relations key String key = entry.getKey(); //Get the corresponding by each pair of corresponding relations value String value = entry.getValue(); System.out.println(key+"="+value); } } }
Note: Map collections cannot be traversed directly using iterators or foreach. But you can use it when you convert it to Set.
1.7 HashMap stores custom type keys
Exercise: Each student (name, age) has his or her own home address. Then, since there is a corresponding relationship, the student object and family address are stored in the map set. The student is the key and the family address is the value.
Note that students with the same name and age are considered to be the same student.
Student class
public class Student { private String name; private int age; //Write the construction method, which has been omitted from the document //To write get,set Method, omitted in the document //To write toString Method, omitted in the document }
Test class
public class HashMapTest { public static void main(String[] args) { //1,Establish hashmap Collection objects. Map<Student,String> map = new HashMap<Student,String>(); //2,Add elements. map.put(new Student("lisi",28), "Shanghai"); map.put(new Student("wangwu",22), "Beijing"); map.put(new Student("zhaoliu",24), "Chengdu"); map.put(new Student("zhouqi",25), "Guangzhou"); map.put(new Student("wangwu",22), "Nanjing"); //3,Take out the elements. Key Value Finding Method Set<Student> keySet = map.keySet(); for(Student key : keySet){ String value = map.get(key); System.out.println(key.toString()+"....."+value); } //Take out the elements. Keypair approach Set<Map.Entry<Student, String>> entrySet = map.entrySet(); for (Map.Entry<Student, String> entry : entrySet) { Student key = entry.getKey(); String value = entry.getValue(); System.out.println(key.toString()+"....."+value); } } }
When storing custom objects in HashMap, if the custom objects exist as key s, then to ensure that the objects are unique, the hashCode and equals methods of the objects must be copied (if you forget, please review HashSet for storing custom objects).
If you want to ensure that the keys stored in the map are in the same order as the keys taken out, you can use the LinkedHashMap collection to store them.
1.8 Static import
In the process of importing a package, we can import the static part directly, so that the static members of a class can be used directly. Static imports often occur in source code.
Static import format:
import static XXX.YYY; YYYY can be used directly after import.
For example: Map.Entry access, simplified to Entry
import static java.util.Map.Entry; public class HashMapTest { public static void main(String[] args) { //1,Establish hashmap Collection objects. Map<Student,String> map = new HashMap<Student,String>(); //Take out the elements. Keypair approach //Set<Map.Entry<Student, String>> entrySet = map.entrySet(); Set<Entry<Student, String>> entrySet = map.entrySet(); //for (Map.Entry<Student, String> entry : entrySet) { for (Entry<Student, String> entry : entrySet) { Student key = entry.getKey(); String value = entry.getValue(); System.out.println(key.toString()+"....."+value); } } }
1.9 Variable parameters
After JDK 1.5, if we define a method that accepts multiple parameters and has the same type of parameters, we can simplify it into the following format:
Modifier Return Value Type Method Name (Parametric Type... Parametric Name) {}
In fact, this writing is completely equivalent to
Modifier Return Value Type Method Name (Parametric Type [] Parametric Name) {}
Only in the latter definition, an array must be passed when invoked, and the former can pass data directly.
After dk1.5. Simplified operations have emerged. In terms of parameters, they are called variable parameters.
The same is for arrays, but when calling this method with variable parameters, it does not need to create an array (that is, the simplicity), but directly passes the elements in the array as actual parameters. In fact, the compiled class file encapsulates these elements into an array first, and then passes them on. These actions are automatically completed when compiling. class files.
Code demonstration:
public class ParamDemo { public static void main(String[] args) { int[] arr = {21,89,32}; int sum = add(arr); System.out.println(sum); sum = add(21,89,32);//Variable parameter invocation form System.out.println(sum); } //JDK1.5 Later writing public static int add(int...arr){ int sum = 0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; } return sum; } //Primitive writing /* public static int add(int[] arr) { int sum = 0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; } return sum; } */ }
The above add method can only exist in one class. Because call uncertainty occurs
Note: If the method has multiple parameters, including variable parameters, the variable parameters must be written at the end of the parameter list.
1.10 Collections collection tool class
Collections are collection tool classes that operate on collections. Some methods are as follows:
Public static < T > void sort (List < T > list) // Set element sorting
//Pre-sorting elements list Set element [33,11,77,55] Collections.sort( list ); //Post-sorted elements list Set element [11,33,55,77]
Public static void shuffle (List <?> list) / / / Collection element storage location disruption
//list Set element [11,33,55,77] Collections.shuffle( list ); //Use shuffle After the method, the elements in the collection are[77,33,11,55],Each time this method is executed, the location of elements stored in the collection is randomly disrupted.
1.11 Set Nesting
Set nesting is not a new knowledge point, but a set of content and a set, such as the nesting of Collection sets, the nesting of Collection sets and Map sets, and the nesting of Map sets.
ArrayList Nested ArrayList
ArrayList< ArrayList<String> >
Collection< ArrayList<Integer> >
Map Nested ArrayList
HashMap<String, ArrayList<Person>>
ArrayList< HashMap<String, String>>
Map Set Nesting
HashMap<String, HashMap<String,String>>
HashMap<String, HashMap<Person,String>>
1.12 Object-Oriented Thought of Collective Inheritance System
Interface: Used to define the functions of all collections, which is equivalent to defining the criteria of collections'functions.
Abstract class: the same way to implement functions in multiple sets is extracted into abstract class implementation, concrete set is no longer overwritten, inheritance can be used;
Specific classes: inherit Abstract classes, implement interfaces, rewrite all abstract methods to achieve a set with specified functions. According to its own data storage structure, each specific collection class implements the functional methods in the interface in different ways.