Day11 Map interface, underlying implementation principle of HashMap and LinkedHashMap, common methods of Map, TreeMap, Hashtable, Properties, Collections and Enumeration

Posted by jstarkweather on Thu, 24 Feb 2022 08:16:20 +0100

1.Map interface


 Map And Collection Exist side by side. Used to save files with Mapping relationship Data :key-value
 Map Medium key and value Can be data of any reference type
 Map Medium key use Set To store, Duplicate is not allowed , i.e. the same Map The class corresponding to the object must override hashCode() and equals() method
 Commonly used String Class as Map Key of
 key and value There is a one-way one-to-one relationship between them, that is, through the specified key A unique and definite value can always be found
 Map Common implementation classes of interface: HashMap , TreeMap , LinkedHashMap And Properties. Among them, HashMap yes Map Implementation class with the most frequently used interface
 * I Map Structure of implementation class:
 *  |----Map:Dual column data, storage key-value Right data   ---Functions similar to high school: y = f(x)
 *         |----HashMap:As Map Main implementation classes of; Unsafe thread and high efficiency; storage null of key and value
 *              |----LinkedHashMap:Guaranteed in traversal map Elements can be traversed in the order of addition.
 *                      Reason: in the original HashMap Based on the 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 that the added key-value Sort and realize sorting traversal. Consider at this time key Natural sorting or custom sorting
 *                      Red and black trees are used at the bottom
 *         |----Hashtable:As an ancient implementation class; Thread safety and low efficiency; Cannot store null of key and value
 *              |----Properties:Commonly used to process configuration files. key and value All String type
 *      HashMap Bottom layer of: array+Linked list( jdk7 (and before)
 *                    array+Linked list+Red black tree( jdk 8)
 *  Interview questions:
 *  1. HashMap The underlying implementation principle of?
 *  2. HashMap and Hashtable Similarities and differences?
 *  3. CurrentHashMap And Hashtable Similarities and differences? (not for the time being)
Copyright notice: This article is CSDN Blogger「lsqstudy」Original articles, follow CC 4.0 BY-SA Copyright agreement, please attach the original source link and this statement for reprint.
Original link:

* II. 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() (take HashMap as an example)
* value in Map: unordered and repeatable. Use Collection to store all values -- > the class where value is located should override equals()
* a key value pair: key value constitutes an Entry object.
* entries in Map: unordered and non repeatable. Use Set to store all entries


 HashMap is the most frequently used implementation class of Map interface.

 Allow use null Key sum null Value, and HashSet Similarly, the order of mapping is not guaranteed.
 The Set composed of all key s is Set: unordered and non repeatable . So, key Class to override: equals() and hashCode()
 The Collection composed of all value s is Collection: unordered and repeatable . So, value Class to override: equals()
 One key-value Form a entry
 The Set composed of all entries is Set: unordered and unrepeatable
 HashMap Judge two key Equal standard Yes: two key adopt equals() Method return true , the hashCode values are also equal.
 HashMap Judge two value Equal standard Yes: two value adopt equals() Method return true .

Underlying implementation principle of HashMap:

JDK 7 and previous versions: HashMap is an array + linked list structure (i.e. chain address method)

After the release of JDK version 8: HashMap is realized by array + linked list + red black tree.



Important constants in HashMap source code:

 *      DEFAULT_ INITIAL_ Capability: default capacity of HashMap, 16
 *      DEFAULT_LOAD_FACTOR: default load factor of HashMap: 0.75
* threshold: critical value of capacity expansion, = capacity * filling factor: 16 * 0.75 = > 12
 *      TREEIFY_THRESHOLD: if the length of the linked list in the Bucket is greater than the default value, it will be converted into a red black tree: 8
 *      MIN_ TREEIFY_ Capability: minimum hash table capacity when nodes in the bucket are trealized: 64

6.4.1 underlying implementation principle of HashMap in JDK7

6.4.2 underlying implementation principle of HashMap in JDK8

6.7. Underlying implementation principle of LinkedHashMap (understand)

6.8 common methods and links in Map are the same as above

6.10 use of two ways of adding TreeMap (NATURAL sorting and customized sorting)


6.13. Properties processing property file

3.Collections -- is the tool class of collection and Map

 Collections is a tool class that operates on collections such as Set, List, and Map
 Collections It provides a series of static methods to sort, query and modify collection elements, and also provides methods to set immutable collection objects and realize synchronous control of collection objects
 Sort operation : (both static Method)
 reverse(List) : reversal List Order of elements in
 shuffle(List) : yes List Random sorting of collection elements
 sort(List) : Assign to elements according to their natural order List The collection elements are sorted in ascending order
 sort(List , Comparator) : According to the specified Comparator Generated sequence pair List Sort collection elements
 swap(List , int , int) : Will specify list In the collection i At element and j Exchange elements at
Find, replace
 Object max(Collection) : Returns the largest element in a given set according to the natural order of the elements
 Object max(Collection , Comparator) : according to Comparator Returns the largest element in a given collection in the specified order
 Object min(Collection)
 Object min(Collection , Comparator)
 int frequency(Collection , Object) : Returns the number of occurrences of the specified element in the specified collection
 void copy(List dest,List src) : will src Copy content from to dest in
 boolean replaceAll(List list , Object oldVal , Object newVal) : Replace all the old values of the List object with the new values

// sorting operations: (all static methods)
//   reverse(List): reverse the order of elements in the List
//   shuffle(List): randomly sort the elements of the List set
//   sort(List): sort the elements of the specified List set in ascending order according to the natural order of the elements
//   sort(List, Comparator): sort the List set elements according to the order generated by the specified Comparator
//   swap(List, int, int): exchange the elements at i and j in the specified list set
    public void Test(){
        List list = new ArrayList();

        Collections.sort(list, new Comparator() {

            public int compare(Object o1, Object o2) {
                if (o1 instanceof Integer && o2 instanceof Integer){
                    Integer i1 = (Integer) o1;
                    Integer i2 = (Integer) o2;

                }else {
                    throw new RuntimeException("The type entered is incorrect");


    //Find, replace
//   Object max(Collection): returns the largest element in a given set according to the natural order of elements
//   Object max(Collection, Comparator): returns the largest element in a given set according to the order specified by the Comparator
//  Object min(Collection)
//  Object min(Collection,Comparator)
//   int frequency(Collection, Object): returns the number of occurrences of the specified element in the specified collection
//   void copy(List dest,List src): copy the contents of src to dest
//   Boolean replaceall (List, Object oldVal, Object newVal): replace all old values of the List object with new values
    public void Test1(){
        List list = new ArrayList();

        List list1 = new ArrayList();

        Object obj = Collections.max(list);
        obj = Collections.min(list);




         * Collections Class provides multiple synchronizedXxx() methods,
         * This method can wrap the specified set into a thread synchronized set, which can solve the problem
         * Thread safety in multithreaded concurrent access to collections
        //The returned list2 is the thread safe list
        List list2 = Collections.synchronizedList(list);

7.2. Supplement: Enumeration (understand!!!)

13: Assemble_ Blog of lsqstudy - CSDN blog

Topics: Java