The last section of the Java collection.
First two sections:
[Java] (XX) Java Collection framework, Collection interface, List interface and implementation classes (ArrayList, Vector, LinkedList)
[Java] (XXI) generic class / interface / method / Set, Set interface and implementation class (HashSet, TreeSet)
6 Map interface and implementation class
- Features of Map interface: store a pair of data (key value), which is out of order and has no subscript. The key cannot be repeated and the value can be repeated.
- Set creation: HashMap < key value data type, value data type > set name = new HashMap < > ();
- method:
(1) Add object
v put(K key,v value) / / store the object in the collection and associate the key value. If the key is repeated, the original value will be overwritten.
(2) Delete object: remove()
(3) Get object (+ enhanced for loop → traversal)
Set<String> keys = map1.keySet();// Returns a set set containing all key values
map collection name. Get (key value) / / obtain the corresponding value according to the key.
map Set name. entrySet() / / Set set with matching key value. getKey() and getValue() get key values respectively.
Collection < V > values() / / returns a collection containing all values.
(4) Judgment: containsKey() and containsValue()
package map; import java.util.HashMap; import java.util.Map; import java.util.Set; public class mapText { public static void main(String[] args) { //Create a Map collection HashMap<String, Integer> map1 = new HashMap<>(); System.out.println("1.Add element"); map1.put("Nike", 1000); map1.put("Lining", 100); map1.put("Adidas", 500); map1.put("Nike", 999);//Repeat key, value override System.out.println(map1.size()); System.out.println(map1); System.out.println("2.Delete element"); map1.remove("Lining");//Delete according to key value System.out.println(map1); //ergodic System.out.println("3.1 adopt keySet()Get key value"); Set<String> keys = map1.keySet();//Returns a set containing all keys for (String key : keys) { System.out.println("{"+key+","+map1.get(key)+"}");//Get the value corresponding to the key } System.out.println("3.2 adopt entrySet()obtain<Key, value>"); for (Map.Entry<String, Integer> stringIntegerEntry : map1.entrySet()) { System.out.println("{"+stringIntegerEntry.getKey()+","+stringIntegerEntry.getValue()+"}"); } System.out.println("4.query"); System.out.println(map1.containsKey("Nike")); System.out.println(map1.containsValue(500)); } } /* 1.Add element 3 {Nike=999, Lining=100, Adidas=500} 2.Delete element {Nike=999, Adidas=500} 3.1 Get the key value through keySet() {Nike,999} {Adidas,500} 3.2 Get < key, value > through entrySet() {Nike,999} {Adidas,500} 4.query true true */
6.1 implementation class of map set
- HashMap [key]: JDK1.2 version has unsafe threads and fast running efficiency; null is allowed as key or value.
- Hashtable: JDK1.0, thread safe and slow running efficiency; null is not allowed as key or value.
- Properties: subclass of Hashtable. Both key and value are required to be strings. It is usually used for reading configuration files.
- TreeMap: implements the SortedMap interface (a sub interface of Map), which can automatically sort key s.
6.2 HashMap class
- Storage structure: hash table (array + linked list + red black tree)
Similar to the HashSet mentioned earlier, the judgment of repetition is based on the hashCode and equals methods, which can be rewritten. [after rewriting, you can insert or delete the corresponding object in the collection through the new keyword] - View the source code analysis summary of HashMap:
(1) When HashMap was first created, the table was null to save space. When the first element was added, the table capacity was adjusted to 16.
(2) When the number of elements is greater than the threshold (16 * 0.75 = 12), the capacity will be expanded, and the size after expansion will be twice the original size, in order to reduce the number of adjusted elements
(3) jdk1.8 when the length of each linked list is > 8 and the number of array elements is ≥ 64, it will be adjusted to a red black tree in order to improve efficiency
(4) jdk1.8 adjust to a linked list when the length of the linked list is less than 6
(5) Before jdk1.8, the linked list was inserted at the head, followed by the tail - The storage structure of HashSet is HashMap. Its add method calls the put method of map and passes the element as the key of map.
A well written HashMap source code analysis: HashMap source code analysis
Default initialization capacity: static final int default_initial_capacity = 1 < < 4; / / aka 16 (arithmetic shift left)
Maximum capacity of array: static final int maximum_capacity = 1 < < 30;
Default load factor: static final float DEFAULT_LOAD_FACTOR = 0.75f;
Create a new Student class:
package map; import java.util.Objects; public class Student { String name; int number; public Student() { } public Student(String name, int number) { this.name = name; this.number = number; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", number=" + number + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; return number == student.number && Objects.equals(name, student.name); } @Override public int hashCode() { return Objects.hash(name, number); } }
HashMap collection using Student class as key:
package map; import java.util.HashMap; public class HashMapText { public static void main(String[] args) { //Create collection HashMap<Student, Integer> map = new HashMap<>(); //Create student object Student s1 = new Student("a11", 2323); Student s2 = new Student("a12", 2345); Student s3 = new Student("a13", 2354); System.out.println("Add objects to the collection"); map.put(s1, 22); map.put(s2, 18); map.put(s3, 20); map.put(new Student("a12", 2345), 3);//Add duplicate keys to update values System.out.println(map); //Delete, traverse, query and Map are consistent (not written) } } /* Add objects to the collection {Student{name='a12', number=2345}=3, Student{name='a13', number=2354}=20, Student{name='a11', number=2323}=22} */
6.3 TreeMap class
- SortedMap interface (a sub interface of Map) is implemented to automatically sort key s.
- Storage structure: red black tree
Similarly, similar to the TreeSet class, implement the Comparable interface in the object class; or use the comparator to customize the comparison. - The storage structure of TreeSet is actually TreeMap. Its add method calls the put method of TreeMap and passes elements into the storage structure as key s.
7 Collections tool class
- Concept: collection tool class, which defines common collection methods other than access.
- method:
Public static void reverse (list <? > list) / / reverse the order of elements in the collection
Public static void shuffle (list <? > list) / / randomly reset the order of collection elements
Public static void sort (list < T > list) / / sort in ascending order (element types must implement the Comparable interface)
package map; import java.util.*; public class UseCollections { public static void main(String[] args) { ArrayList<Integer> listset = new ArrayList<>(); listset.add(100); listset.add(34); listset.add(25); listset.add(33); System.out.println("Original set ArrayList: "+listset); Collections.sort(listset); System.out.println("Sort set ArrayList: "+listset); int i = Collections.binarySearch(listset, 33); System.out.println("Serial number of binary search 33:"+i); ArrayList<Integer> list2 = new ArrayList<>(); for (int i1 = 0; i1 < listset.size(); i1++) {//Open up space list2.add(0); } Collections.copy(list2, listset); System.out.println("Copy Collection list2: "+list2); Collections.reverse(list2); System.out.println("Sequence after inversion:"+list2); Collections.shuffle(list2); System.out.println("Upset:"+list2); //list to array Integer[] arr=list2.toArray(new Integer[0]); System.out.println(arr.length); //Convert array to collection String[] nameStrings= {"LU","MA","YANG"}; List<String> list3 = Arrays.asList(nameStrings);//Restricted collection, cannot be added or deleted // list3.add("aa"); / / compilation error System.out.println(list3); } } /* Original set ArrayList: [100, 34, 25, 33] Sort set ArrayList: [25, 33, 34, 100] Serial number of binary search 33: 1 Copy set list2: [25, 33, 34, 100] Sequence after inversion: [100, 34, 33, 25] Disruption: [33, 34, 100, 25] 4 [LU, MA, YANG] */