Java Collection Learning (14) Map Summary

Source: Internet
Author: User
Tags abstract definition count delete key hash implement serialization thread

Map Summary (HASHMAP, Hashtable, TreeMap, Weakhashmap and other usage scenarios)

After we've learned all about map, we'll go back and open the map frame.

The 1th part of map generalization

The map is an abstract interface to the "key-value pair" mapping. The Abstractmap implements most of the function interfaces in the map. It reduces the repetitive encoding of "Map implementation Classes". SortedMap an ordered "key value pair" mapping interface. Navigablemap is an interface that inherits from SortedMap and supports navigation functions. HashMap, Hashtable, TreeMap, weakhashmap these 4 classes are the implementation classes of the "key value pair" mapping. They all have their differences!

HashMap is a hash table based on the "zipper method" implementation. Typically used in single-threaded programs. Hashtable is also based on the "zipper method" implementation of the hash table. It is commonly used in multithreaded programs. Weakhashmap is also based on the "zipper method" implementation of the hash table, it is generally used in single-threaded programs. When a "weak key" is reclaimed by GC, its corresponding key-value pair is also removed from the Weakhashmap when the key is "weak key" in Hashmap,weakhashmap, and the key in HashMap is a strong key. TreeMap is an ordered hash table, which is implemented through a red-black tree. It is typically used to store ordered mappings in a single thread.

The similarities and differences of the 2nd part HashMap and Hashtable

Part 2.1 The same point of HashMap and Hashtable

Both HashMap and Hashtable are hash lists that store "key value pairs (Key-value)", and are all implemented using the Zipper method. Stored in the idea is: stored through the table array, each element of the array is a entry, and a entry is a one-way list, entry the list of each node to save the Key-value key value pairs of data.

Add Key-value Key value pairs: First, calculate the hash value based on the key value, and then compute the array index (that is, the Key-value index in the table). Then, according to the array index to find entry (that is, one-way linked list), and then traverse the one-way list, the key and the list of each node in the key to compare. If the key already exists in the entry list, replace the old value value with the value; If the key does not exist in the entry list, create a new Key-value node and insert the node into the table header position of the entry list. Delete Key-value key value pairs: Delete key value pairs, compared to "add key value pairs", it is much simpler. First, the hash value is computed based on key, and the array index (that is, the index of the Key-value in the table) is computed. Then, according to the index to find entry (that is, one-way linked list). If the node Key-value exists in the linked list entry, delete the nodes in the linked list.

The above describes the similarities between HashMap and Hashtable. It is because they are hash lists that we focus more on "their differences and the circumstances under which they are used". Next, we'll look at the difference.

Part 2.2 Differences between HashMap and Hashtable.

1 inheritance and implementation different ways

HashMap inherits from Abstractmap, realizes map, cloneable, java.io.Serializable interface. Hashtable inherits from Dictionary, realizes map, cloneable, java.io.Serializable interface.

Definition of HashMap:

Publicclass hashmap<k,v>
    extends abstractmap<k,v>
    implements Map<k,v>, Cloneable, Serializable {...}

Definition of Hashtable:

Publicclass hashtable<k,v>
    extends dictionary<k,v>
    implements Map<k,v>, Cloneable, java.io.Serializable {...}

From this, we can see that: 1.1 HashMap and Hashtable both implement map, cloneable, java.io.Serializable interface. Implements the map interface, which means that they all support key-value key value pairs operations.   Basic Key-value key value pairs such as add Key-value key pair, get key, get value, get map size, empty map, and so on are supported.   Implements the Cloneable interface, which means it can be cloned. Implements the Java.io.Serializable interface, meaning that they support serialization and can be transmitted through serialization.

1.2 HashMap inherits from Abstractmap, and Hashtable inherits from Dictionary is an abstract class that inherits directly from the object class and does not implement any interfaces. The dictionary class is introduced by JDK 1.0. Although dictionary also supports basic operations such as "Add key-value key value pair", "Get Value", "Get Size", its API functions are less than map, and dictionary is typically traversed by enumeration (enumeration class), map is traversed through the iterator (iterator). However, ' because Hashtable also implements the map interface, it supports enumeration traversal and iterator traversal.   This is further explained later. Abstractmap is an abstract class that implements most of the API functions of the map interface and provides a great convenience for the specific implementation classes of map. It is the new class for JDK 1.2.

2 Thread safety is different

Almost all functions of Hashtable are synchronized, that is, it is thread-safe and supports multithreading. The HashMap function is not synchronized, and it is not thread-safe. To use HashMap in multiple threads, we need additional synchronization. Synchronization of HashMap can be done using the Synchronizedmap static method provided by the collections class, or directly using the Concurrenthashmap class in the Java.util.concurrent package provided after JDK 5.0.

3 The handling of null values is different

HashMap's key or value can be null. Hashtable key and value cannot be assumed null.

Let's look at the HashMap and Hashtable "Add Key-value" method first.

The method of adding Key-value to HashMap

Add "Key-value" to HashMap public V-Put (K key, V value) {//if "key is null", add the key value pair to table[0].
    if (key = = null) return Putfornullkey (value);
    If "key is not NULL," the hash value of the key is computed and then added to the list corresponding to the hash value.
    int hash = hash (Key.hashcode ());
    int i = indexfor (hash, table.length);
        for (entry<k,v> e = table[i]; e!= null; e = e.next) {Object K; If the key value pair of "This key" already exists, replace the old value with the new value.
        And then quit!
            if (E.hash = = Hash && ((k = e.key) = = Key | | key.equals (k))) {V oldValue = E.value;
            E.value = value;
            E.recordaccess (this);
        return oldValue;
    }//If the corresponding key value pair does not exist, add "Key-value" to the table modcount++;
    AddEntry (hash, key, value, I);
return null;  The purpose of the//Putfornullkey () is to add "key to null" key value pair to table[0] position private V Putfornullkey (v value) {for (entry<k,v> e = TABLE[0]; e!= null;
            E = e.next) {if (E.key = = null) {V oldValue = E.value; E.Value = value;
            The recordaccess () function does nothing e.recordaccess (this);
        return oldValue;
    }//Add the 1th "key null" element to the table when it will be executed here.
    It does this by setting the key of "set table[0" to null and the value to "."
    modcount++;
    AddEntry (0, NULL, value, 0);
return null; }

Hashtable Add Key-value method

Add ' Key-value ' to hashtable public synchronized V-put (K key, V value) {//Hashtable cannot insert a value NULL element!!!
    if (value = = null) {throw new NullPointerException ();
    //If the key value pair already exists in the Hashtable, the//will replace the old value Entry tab[with the new value = table;
    Cannot insert key-null element in Hashtable!!!
    Otherwise, the following statement throws an exception!
    int hash = Key.hashcode ();
    int index = (hash & 0x7fffffff)% Tab.length; for (entry<k,v> e = Tab[index]; e!= null; e = e.next) {if (E.hash = hash) && e.key.equals (key)
            ) {V old = E.value;
            E.value = value;
        return old;
    }//If the key value pair for key is not present in the Hashtable,//(01) "Modify Statistics" +1 modcount++; (02) If "Hashtable actual capacity" > "threshold" (threshold = Total capacity * load factor)//Adjust hashtable size if (count >= threshold) {//Reh
     
        Ash the table if the threshold is exceeded rehash ();
        tab = table;
  Index = (hash & 0x7fffffff)% Tab.length;  (03) Save the Entry (list) in the "Hashtable index" position to e entry<k,v> e = Tab[index];        
    (04) Create "New entry node" and insert "new entry" into "Hashtable's index position" and set E as the next element of "new entry" (That is, "new entry" as the linked table header).
    Tab[index] = new entry<k,v> (hash, key, value, E);
    (05) "Hashtable actual capacity" +1 count++;
return null; }

Based on the above code, we can see:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.