Map interface
summary
Java.util interface map < K, V >
Type parameter: K - indicates the key maintained by this mapping; V - indicates the corresponding value maintained by this mapping
It is also called hash table and hash table. It is often used for data of key value pair structure. The key cannot be repeated, and the value can be repeated
characteristic
- Map can extract the corresponding value according to the key
- Map keys cannot be repeated. If they are repeated, the corresponding values will be overwritten
- Map stores unordered data
- The initial capacity of the Map is 16, and the default loading factor is 0.75
TIPS: excerpt of source code:
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
Initial capacity 1 < < 4, equivalent to 1 * (2 ^ 4), i.e. 16
static final float DEFAULT_LOAD_FACTOR = 0.75f;
The default loading factor is 0.75f, that is, when 75% is saved, the capacity will be expanded according to the power of 2
Inheritance structure
common method
Just learn the methods in the Map interface
void clear() removes all mapping relationships from this mapping (optional operation) boolean containsKey(Object key) returns true if this mapping contains mapping relationships for the specified key
boolean containsValue(Object value) returns true if this mapping maps one or more keys to the specified value
Set < map. Entry < K, V > > entryset() returns the set view of the mapping relationships contained in this map
boolean equals(Object o) compares whether the specified object is equal to this mapping
V get(Object key) returns the value mapped by the specified key; Returns null if the mapping does not contain a mapping relationship for the key
int hashCode() returns the hash code value of this mapping
boolean isEmpty() returns true if the mapping does not contain a key value mapping relationship
Set keySet() returns the set view of the keys contained in this map
V put(K key, V value) associates the specified value with the specified key in this map (optional)
Void putall (map <? Extensions K,? Extensions V > m) copies all mapping relationships from the specified map to this map (optional)
V remove(Object key) if there is a key mapping relationship, remove it from this mapping (optional operation)
int size() returns the number of key value mapping relationships in this mapping
Collection values() returns a collection view of the values contained in this map
Exercise: Map common method test
Create package: cn.tedu.map
Create class: MapDemo.java
package cn.tedu.list; import java.util.*; /**This class is used to test the Map interface*/ public class MapDemo { public static void main(String[] args) { //1. Create a Map object /**Map The data in must comply with the mapping rules. Be sure to specify the K and V data types at the same time * The specific types of K and V depend on the specific business requirements*/ Map<Integer,String> map = new HashMap<>();//Note: java.util //2. Store data into the map set. Note that the method is put(), and a pair of < K, V > values need to be stored map.put(9527,"Baigujing"); map.put(9528,"Black bear essence"); map.put(9529,"Carp essence"); map.put(9530,"Yellow hair monster"); map.put(9531,"Black bear essence"); map.put(9527,"Daughter country King"); /**1.map There are disordered data stored in * 2.map The value in can be repeated - for example, we can save two black bear spirits * 3.map The key in cannot be repeated. If it is repeated, the following value will overwrite the previous value * For example, the king of the daughter country and the white bone essence are 9527, and the white bone essence is covered*/ System.out.println(map);//Check whether the data in the map collection is saved successfully //3. Conduct method test //map.clear();// Empty collection System.out.println(map.hashCode());//Gets the hash code of the collection System.out.println(map.equals("Yellow hair monster"));//Determine whether the "yellow hair monster" is equal to the collection object System.out.println(map.isEmpty());//Determine whether the collection is empty System.out.println(map.size());//Gets the number of elements in the collection //Determines whether the current map collection contains the specified Key System.out.println(map.containsKey(9527));//true //Determines whether the current map collection contains the specified Value System.out.println(map.containsValue("Baigujing"));//false because it has been overwritten //Get the corresponding value value according to the key value System.out.println(map.get(9530)); //According to the key value pair corresponding to this key value, K and V are deleted System.out.println(map.remove(9529)); System.out.println(map.containsKey(9529)); System.out.println(map.containsValue("Carp essence")); //Take out all value s in the map Collection and put them into the Collection collection //The Type of Type in collection < Type > depends on the Type of value in the map Collection<String> values = map.values(); System.out.println(values);//[daughter country king, black bear spirit, yellow hair monster, black bear spirit] //4.map set iteration method 1 /**Mode 1: * Traverse the data in the map, but the map itself does not have an iterator, so it needs to be converted into a set set first * Set<Key>:Store all key values in the map into the set -- keySet()*/ //4.1 take out the key value in the map set and store it in the set set. The generic type of the set is the type Integer of the key Set<Integer> keySet = map.keySet(); //4.2 to traverse a set, you need to get the iterator of the set Iterator<Integer> it = keySet.iterator(); //4.3 all elements in the loop iteration set while(it.hasNext()){//Determine whether the next element can be iterated Integer key = it.next();//Get the key of the map obtained in this cycle String value = map.get(key); System.out.println("{"+key+","+value+"}"); } /**Mode 2: * To traverse the map set, you need to convert the map set into a set set first * Is to put a pair of key & value pairs in the map into the set as an entry < K, V > * A pair of K and V is an Entry*/ Set<Map.Entry<Integer, String>> entrySet = map.entrySet(); //Get iterator Iterator<Map.Entry<Integer, String>> it2 = entrySet.iterator(); while(it2.hasNext()){//Determines whether the next element can be iterated //An Entry object traversed in this round Map.Entry<Integer, String> entry = it2.next(); Integer key = entry.getKey();//Get the key in the Entry String value = entry.getValue();//Get value in Entry System.out.println("{"+key+","+value+"}"); } } }
HashMap
preface
The key of HashMap should override hashCode() and equlas() at the same time
hashCode() is used to determine whether the hash values of the two are the same. After rewriting, it is generated according to the attribute
equlas() is used to determine whether the values of attributes are the same. After rewriting, it is determined according to the attributes
– equlas() judges that if the data are equal, hashCode() must be the same
– equlas() judges that if the data are not equal, hashCode() should be as different as possible
Stored procedure for HashMap
- The structure of HashMap is in the form of array + linked list or array + red black tree
- The Entry [] array at the bottom of HashMap has an initial capacity of 16, a loading factor of 0.75f, and a capacity expansion of about twice
- When storing data, the data storage location will be calculated according to the hash(key)%n algorithm. N is the length of the array, which is actually the capacity of the set
- When no data has been saved before the calculated location, the data will be stored directly
- When there is data in the calculated position, hash collision / hash collision will occur
The solution is to adopt the structure of linked list and insert new elements after the elements in the array
In other words, the elements in the array are the first nodes added - If the length of the linked list is > 8 and the array length is > 64, the linked list will be turned into a red black tree. When the length of the linked list is < 6, the red black tree will be restored to a linked list again
Exercise: get the data of HashMap
Create package: cn.tedu.map
Create class: TestHashMap.java
package cn.tedu.collection; import java.util.HashMap; /**This class is used for HashMap exercises*/ public class TestHashMap { public static void main(String[] args) { //Create a HashMap object HashMap<Integer,String> map = new HashMap(); /** * Source code excerpt: * static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 * The initial capacity is 1 < < 4, which is equivalent to 1 * (2 ^ 4) = 16 * static final float DEFAULT_LOAD_FACTOR = 0.75f; * The default loading factor is 0.75, that is, when 75% is saved, the capacity will be expanded according to the power of 2 */ /* * When the loading factor of the capacity is reached, the space will be reopened and the storage location of all objects will be recalculated, which is also called rehash * When setting the initial capacity and loading factor, we should pay attention to the relative balance. If the loading factor is too low, rehash is too frequent, which will affect the performance * If the initial capacity is set too high or the load factor is set too high, the query efficiency will be affected */ } }
Exercise: character statistics in strings
Create package: cn.tedu.map
Create class: TestMap.java
package cn.tedu.map; import java.util.HashMap; import java.util.Map; import java.util.Scanner; /*This class is used to practice the map case: counting the number of characters in a string * Demand effect: user input aabbbcc, output: a=2,b=3,c=2*/ public class TestMap2 { public static void main(String[] args) { //1. Receive the string entered by the user System.out.println("Please enter the string to be counted:"); String input = new Scanner(System.in).nextLine(); //2. Prepare a map set to store the Character and the number of characters Integer //Why is the Character type Character used as the key in the map? Because the key cannot be repeated, but the number of times can be repeated Map<Character,Integer> map = new HashMap<>(); //3. Prepare the data to be stored in the map: K and V //3.1 traverse the string entered by the user and count each character for (int i = 0; i < input.length(); i++) { //3.2 get the characters traversed in this cycle char key = input.charAt(i); //System.out.println(key);// Print and view the characters obtained in each cycle. There is no problem //3.2 get the corresponding value according to the obtained key Integer value = map.get(key);//According to the character, get the number of times this character is saved in the map if(value == null){//This character has not appeared before, and the number of times is still the default value of Integer null map.put(key,1);//If it does not appear, the number is set to 1 }else {//value is not null, else map.put(key,value+1);//This character has appeared before, and the number of times becomes the previous number + 1 } } System.out.println("The number of occurrences of each character is:"+map); } }
set interface
summary
Set is a Collection that does not contain duplicate data
The data in the Set collection is out of order (because the Set collection has no subscript)
The elements in the Set cannot be repeated - they are often used to de duplicate data
Characteristics of Set
- The data is out of order and cannot be duplicated
- HashSet: the bottom layer is the hash table, which wraps the HashMap, which is equivalent to storing the data as K in the internal HashMap when storing the data in the HashSet. Of course, K is still not allowed to repeat.
- TreeSet: the bottom layer is TreeMap, which is also in the form of red black tree, which is easy to find data
common method
Just learn the methods in the Collection interface
HashSet
summary
The bottom layer is a hash table wrapped with HashMap, which is equivalent to storing data into the HashSet as K in the internal HashMap. K is not allowed to be repeated and null is allowed
Exercise: Set related tests
Create package: cn.tedu.collection
Create class: TestSet.java
package cn.tedu.collection; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /*This class is used to test Set*/ public class TestSet { public static void main(String[] args) { //1. Create the corresponding collection object Set<String> set = new HashSet<>(); //2. Data storage set.add("Zixia Fairy"); set.add("Supreme treasure"); set.add("spider goblin"); set.add("Zixia Fairy"); set.add(null); /*1.set The elements in the collection are out of order * 2.set Elements in a collection cannot be duplicated * 3.set A collection can hold null values, but there is only one at most*/ System.out.println(set);//[spider spirit, null, zhizunbao, Zixia fairy] //3. Common test methods System.out.println(set.contains("Tang Monk"));//false to determine whether the specified element is included System.out.println(set.isEmpty());//false to judge whether it is empty System.out.println(set.remove(null));//true to remove the specified element System.out.println(set);//[spider essence, supreme treasure, Zixia fairy] System.out.println(set.size());//3. Get the number of elements in the set System.out.println(Arrays.toString(set.toArray()));//[spider essence, supreme treasure, Zixia fairy], turn the collection into an array //4.1 create set2 set and store data in the set Set<String> set2 = new HashSet<>(); set2.add("Rabbit paper"); set2.add("Cerebellar axe"); set2.add("Xiaohaitong"); set2.add("veal "); System.out.println(set2);//[rabbit paper, xiaohaitong, calf, cerebellar axe] System.out.println(set.addAll(set2));//Add all the elements of the set2 set to the set set System.out.println(set);//[spider essence, rabbit paper, xiaohaitong, zhizunbao, calf, cerebellar axe, Zixia fairy] System.out.println(set.containsAll(set2));//Judge whether all elements of set2 set are in set set System.out.println(set.removeAll(set2));//Delete all elements belonging to the set2 set in the set set System.out.println(set);//[spider essence, supreme treasure, Zixia fairy] System.out.println(set.retainAll(set2));//Only the common elements belonging to the set and set2 sets in the set set are reserved System.out.println(set);//[] //5. Iteration of sets Iterator<String> it = set2.iterator();//5.1 get iterator of collection while(it.hasNext()) {//5.2 judge whether the set has the next element String s = it.next();//5.3 if yes, loop through to get the currently traversed element System.out.println(s); } } }
Exercise: Set related test 2
Create package: cn.tedu.collection
Create class: Student.java
package cn.tedu.collection; import java.util.Objects; //1. Create a custom reference type Student public class Student { //2. Create attributes String name;//full name int id;//Student number //3. Provide full parameter structure of this class public Student(String name, int id) { this.name = name; this.id = id; } //3.2 toString() for student class @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", id=" + id + '}'; } //3.3 add equals() and hashCode() rewritten by student class @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; return id == student.id && Objects.equals(name, student.name); } @Override public int hashCode() { return Objects.hash(name, id); } }
Exercise: Set related test 2
Create package: cn.tedu.collection
Create class: TestSet2.java
package cn.tedu.collection; import java.util.HashSet; import java.util.Set; /*This class is used to further test set*/ public class TestSet2 { public static void main(String[] args) { //4. Create a set object set Set<Student> set = new HashSet<>(); //5. Create an object of custom class Student Student s1 = new Student("Zhang San",3); Student s2 = new Student("Li Si",4); Student s3 = new Student("Li Si",4); //6. Store the created Student object in the set set set.add(s1); set.add(s2); set.add(s3); /*If the type stored in set is our custom type * You need to add overridden equals() and hashCode() to the custom class to remove the duplicate * Otherwise, it will be considered that the address values of s2 and s3 are different. They are two different objects and will not be duplicated*/ System.out.println(set); } }
expand
HashMap expansion
Growth factor:
static final float DEFAULT_LOAD_FACTOR = 0.75f;
The previous description has found that when your space is only 10, it is easy to cause the address corresponding to the hashcode of two objects to be one location. This will cause two objects to form a hash bucket (linked list). At this time, there is a parameter of loading factor. The default value is 0.75. If you have 100 hashmap space, the hashmap needs to be expanded when you insert 75 elements. Otherwise, a long hash bucket structure will be formed, and the time will be increased for query and insertion, because it needs to compare equals one by one. But you can't make the loading factor very small, such as 0.01, which is obviously inappropriate. Frequent capacity expansion will greatly consume your memory. At this time, there is a balance. The default value in jdk is 0.75. Of course, the load factor can be adjusted according to your actual situation.