Http://www.cnblogs.com/skywang12345/p/3311126.html
Overview
After learning all the contents of map, we'll turn to the map Frame.
The contents of this chapter Include:
Part 1th Map Overview
The similarities and differences of HashMap and Hashtable in the 2nd part
The similarities and differences of HashMap and Weakhashmap in the 3rd part
Reprint Please specify source: http://www.cnblogs.com/skywang12345/admin/EditPosts.aspx?postid=3311126
part 1th Map Overview
Map is an abstract interface for "key-value pairs" mappings.
Abstractmap implements most of the function interfaces in the MAP. It reduces the repeated encoding of the "MAP implementation class".
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 implementation classes for "key-value pairs" mappings. They are different!
HashMap is a hash table based on the "zipper method". Typically used in single-threaded programs.
Hashtable is also a hash table based on the "zipper method". It is generally used in multithreaded Programs.
Weakhashmap is also a hash table based on the "zipper" method, which is also commonly used in single-threaded Programs. When a weak key is reclaimed by gc, its corresponding key-value pair is also removed from the weakhashmap, while the key in HashMap is a strong key, compared to the key in Hashmap,weakhashmap.
TreeMap is an ordered hash list, which is implemented by Red-black Trees. It is typically used for storing ordered mappings in a single thread.
the similarities and differences of HashMap and Hashtable in the 2nd part
Part 2.1 The same point of HashMap and Hashtable
HashMap and Hashtable are both hash lists that store "key-value pairs (key-value)", and are all implemented using the zipper method.
The idea of storage is that each element of an array is a entry through the table array, and a entry is a one-way list, andeach node in the entry list holds the Key-value key-value pair of data .
add Key-value key-value pairs : first, The hash value is computed based on the key value, and then the array index (that is, the Key-value index in the Table)is Computed. then, based on the array index, find entry (that is, a one-way list), and then traverse the one-way list to compare key to each node in the List. If the key already exists in the entry list, replace the old value value with that value, and if the key does not exist in the entry linked list, create a new key-value node and insert the node into the header position of the entry linked List.
Delete key-value key -value pairs: Deleting a key-value pair is much simpler than adding a key-value pair. first, The hash value is computed based on key, and then the array index (that is, the Key-value index in the Table) is computed. then, Find the entry (that is, the one-way list) based on the index. If the node Key-value exists with the linked list entry, the nodes in the linked list are Deleted.
The same points of HashMap and Hashtable are described Above. It is because they are hash lists that we focus more on "the difference between them and the circumstances in which they are suitable for use". then, Let's look at the difference between them First.
Part 2.2 Differences between HashMap and Hashtable
1 inheritance and implementation in different ways
HashMap inherits from abstractmap, and realizes the map, cloneable, java.io.Serializable interface.
Hashtable inherits from dictionary, and realizes the map, cloneable, java.io.Serializable interface.
Definition of Hashmap:
public class hashmap<k,v> extends abstractmap<k,v> implements map<k,v>, cloneable, Serializable {...}
Definition of Hashtable:
public class hashtable<k,v> extends dictionary<k,v> implements map<k,v>, cloneable, Java.io.Serializable {...}
From this, we can see:
1.1 HashMap and Hashtable both implement the map, cloneable, and java.io.Serializable Interfaces.
The map interface is implemented, meaning that they all support key-value Key-value pair Operations. Basic Key-value key value pairs such as "add key-value key pair", "get key", "get value", "get map size", "clear map" are Supported.
Implements the Cloneable interface, which means it can be cloned.
Implements the Java.io.Serializable interface, which means that they support serialization and can be transmitted by Serialization.
1.2 HashMap inherits from abstractmap, and Hashtable inherits from dictionary
Dictionary is an abstract class that inherits directly from the object class and does not implement any Interfaces. The dictionary class was introduced in JDK 1.0. Although dictionary also supports basic operations such as "add Key-value key-value pair", "get value", "get size", but its API function is less than map, and dictionary is usually through enumeration (enum Class) to traverse, map is to traverse through the iterator (iterator). however, because Hashtable also implements the map interface, it supports enumeration traversal as well as 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 great convenience for the specific implementation classes of the MAP. It is a new class for JDK 1.2.
2 Thread safety is different
Almost all functions of Hashtable are synchronous, that is, it is thread-safe and supports Multithreading.
The HashMap function is unsynchronized, and it is not thread-safe . In order to use HashMap in multi-threading, we need to perform additional synchronous processing. Synchronous processing of HashMap can use the Synchronizedmap static method provided by the collections class, or the Concurrenthashmap class in the Java.util.concurrent package provided after JDK 5.0 is used Directly.
3 handling of NULL values is different
The HashMap key and value can be null.
The Hashtable key and value are not nullable.
Let's take a look at HashMap and Hashtable. "add key-value" method
The method of adding Key-value to HashMap
View Code
The method of adding Key-value to Hashtable
View Code
According to the above code, we can see:
hashtable key or value cannot be a null! otherwise, An exception nullpointerexception is Thrown.
the HashMap key and value can be Null. when HashMap key is null, HashMap inserts it into the table[0] position (that is, The first position of the HashMap hash table), and table[0] will only hold a value of NULL for the KEY. When multiple key null values are inserted, table[0] retains the last inserted Value.
4 supported traversal types are different
HashMap only supports iterator (iterator) Traversal.
Hashtable supports both iterator (iterators) and enumeration (enumerators) Traversal.
Enumeration is the interface that JDK 1.0 adds, only hasmoreelements (), nextelement () Two API interfaces, and cannot be modified by the enumeration () Element.
The iterator is a JDK 1.2 add-on interface that supports Hasnext (), next (), and remove () three API Interfaces. HashMap is also added to JDK version 1.2, so iterator instead of Enumeration,hashmap only supports iterator Traversal.
5 The order of traversal is different when traversing through a iterator iterator
The HashMap is a "forward- backward" Traversal of an array, and a linked list of specific items of a group is iterated from the table Header.
Hashtabl is a "forward" traversal of an array, and then a list of specific items corresponding to the linked list, starting from the table header to Traverse.
Both HashMap and Hashtable implement the map interface, so they support getting their "key collection", "value collection", "key-value collection", and then iterating through the collections Iterator.
Since the traversal principle of "key collection", "value collection", "key-value collection" is the same, i'll walk through the "key-value collection" to illustrate This.
The way HashMap and Hashtable traverse the Key-value collection is: (01) get the Map.entry collection through EntrySet (). (02) get the "map.entry collection" iterator through iterator () and Iterate.
The implementation of the hashmap: the first "backward" traversal of the array, the list of specific items corresponding to the linked list, from the beginning of the table to traverse Backward.
View Code
The implementation of the hashtable: first from the "backward forward" traversal of the array, the list of specific items corresponding to the linked list, from the beginning of the table to traverse Backward.
View Code
6 The initial value of the capacity and the increment method are different
HashMap The default capacity size is; When you increase capacity, you change the capacity to "raw capacity x2"at a Time.
Hashtable The default capacity size is one, and when the capacity is increased, the capacity is changed to " raw capacity x2 + 1" at a Time.
HashMap The default "load factor" is 0.75, and the default capacity size is 16.
View Code
When the HashMap "actual capacity" >= "threshold" (threshold = Total capacity * Load factor), the capacity of the HashMap is Doubled.
View Code
Hashtable The default "load factor" is 0.75, and the default capacity size is 11.
View Code
When the Hashtable "actual capacity" >= "threshold" (threshold = Total capacity x load factor), It will become "raw capacity x2 + 1".
View Code
7 The hash value algorithm is different when adding key-value
HashMap when adding elements, a custom hashing algorithm is Used.
Hashtable does not have a custom hashing algorithm, but directly takes the hashcode () of the Key.
HashMap when adding elements, a custom hashing algorithm is Used.
View Code
Hashtable does not have a custom hashing algorithm, but directly takes the hashcode () of the Key.
View Code
8 parts of the API are different
Hashtable supports the contains (Object Value) method and overrides the ToString () method ;
While HashMap does not support the contains (Object Value) method, the ToString () method is not Overridden.
finally, say "hashmap and hashtable" use of the SCENE.
In fact, If you understand the differences between them, it is easy to distinguish between the choice according to the Situation. For Example: (01) If in a single thread, we tend to choose hashmap, while in multi-threading, the Hashtable is Selected. (02), If you cannot insert a null element, select hashtable; otherwise, you can select Hashmap.
But this is not an absolute standard. For example, in multi-threading, we can either synchronize the HashMap ourselves or choose concurrenthashmap. When both HashMap and Hashtable are unable to meet their own needs, you can also consider a new definition of a class, inheriting or re-implementing a hash table, and, of course, is not required in General.
the similarities and differences of HashMap and Weakhashmap in the 3rd part
3.1 HashMap and weakhashmap the same point
1 They are both hash lists and store "key-value pairs" mappings.
2 They all inherit from Abstractmap and implement the map Foundation.
3 They all have the same constructor functions.
They all include 4 constructors, and the parameters of the functions are the Same.
4 The default capacity size is 16, and the default load factor is 0.75.
5 their "key" and "value" are allowed to be null.
6 They are all "unsynchronized."
3.2 The differences between HashMap and WEAKHASHMAP.
1 HashMap implements the cloneable and serializable interfaces, and Weakhashmap does Not.
HashMap implements cloneable, meaning it can clone itself through clone ().
HashMap implementation of serializable means that it supports serialization and can be transmitted by Serialization.
2 hashmap "key" is "strong reference (strongreference)", and weakhashmap's key is "weak reference (weakreference)".
The "weak key" of WeakReference can realize the dynamic recovery of "key-value pair" by Weakreference. When the "weak key" is no longer used, the GC reclaims it, and WeakReference also deletes the key-value pair corresponding to the weak key.
This "weak key" implementation of the dynamic recovery "key value pair" principle? In fact, it is implemented by WeakReference (weak Reference) and Referencequeue (reference queue). first, we need to understand the weakhashmap:
first, "key" is weakreference, that is, key is weak key.
second, Referencequeue is a reference queue, which is used in conjunction with WEAKHASHMAP. When the object referenced by the weak reference is garbage collected, the Java Virtual machine adds the weak reference to the reference queue associated with it. The Referencequeue in Weakhashmap is the Queue.
thirdly, Weakhashmap is implemented by an array, and we assume that the array is a table.
next, talk about the steps for "dynamic recycling."
Create a new Weakhashmap and add a Key-value pair to the weakhashmap.
When you add a Key-value pair to weakhashmap, the key you add is a weak key.
In fact, Weakhashmap is a entry (key-value Pair) saved by an array table, and each entry is actually a one-way list, that is, the entry is a list of Key-value Pairs.
When a "weak key" is no longer referenced by another object and is recycled by gc. When the "weak key" is reclaimed by the gc, the "weak key" is also added to the Queue.
For example, when we add a "weak key" key to weakhashmap, we later set the key to Null. At this point, there is no external external object to reference the key Again.
then, when the GC of the Java Virtual Machine reclaims memory, The associated memory of key is reclaimed, and the key is added to the Queue.
(03) the next time we need to manipulate weakhashmap, the table and queue are synchronized First. All of the key-value pairs are saved in the table, and the "weak keys" that are collected by GC are saved in the queue, and they are deleted by deleting the key-value pairs corresponding to the "weak keys" retrieved by GC in the Table.
For example, when we "read an element in a weakhashmap or get the size of a weakreference", it synchronizes the table and queue first to "delete the key-value pairs corresponding to the ' weak keys ' that are collected by GC in the table." The method of deletion is to compare the ' key ' of the elements in table and the ' key ' in the queue, and if they are equivalent, delete the key-value pair in Table.
3.3 HashMap and Weakhashmap comparison test procedure
View Code
Operation Result:
--HashMap--map entry:h2-h2 Map size:1--weakhashmap--map entry:w2-w2 map Size:1--self-def HashMap-- Map entry: [email protected]-s4 map size:1--self-def weakhashmap--gc self:id=10 [email protected]) map entry: [ Email protected]-s2 Map size:1
Java Collection Series 14 Map summary (HashMap, Hashtable, TreeMap, Weakhashmap and other usage SCENARIOS)