HashMap, HashTable, LinkedHashMap, and TreeMap

Source: Internet
Author: User

Java defines an interface java. util. Map for ing in the data structure. It has four implementation classes: HashMap, HashTable, LinkedHashMap, and TreeMap. This section describes the usage and differences of the four instances.
Key Technology Analysis:
Map is used to store key-value pairs and obtain values based on keys. Therefore, duplicate keys are not allowed, and duplicate values are allowed.
L (1) HashMap is the most commonly used Map. It stores data based on the hashCode value of the key and can directly obtain its value based on the key, with fast access speed. HashMap allows a maximum of null keys for one record, but does not allow null values for many records. HashMap does not support thread synchronization. At any time, multiple threads can write HashMap at the same time, which may cause data inconsistency. If synchronization is required, you can use the Collections. synchronizedMap (HashMap map) method to synchronize HashMap.
L (2) Hashtable is similar to HashMap. The difference is that it does not allow null keys or values to be recorded. It supports thread synchronization, that is, only one thread can write Hashtable at any time, however, this also leads to a slow write speed for Hashtable.
L (3) LinkedHashMap stores the record insertion sequence. When Iteraor is used to traverse LinkedHashMap, the first record must be inserted first. It is slower than HashMap during traversal. All features of HashMap are available.
L (4) TreeMap can sort the records stored by the key. By default, the records are sorted in ascending order. You can also specify the comparator for sorting. When Iteraor is used to traverse TreeMap, the obtained records are sorted in ascending order. The keys and values of TreeMap cannot be empty.
 
Import java. util. HashMap;
Import java. util. Hashtable;
Import java. util. Iterator;
Import java. util. LinkedHashMap;
Import java. util. Map;
Import java. util. TreeMap;
 
 
Public class TestMap {
 
 
Public static void init (Map map ){
If (map! = Null ){
String key = null;
For (int I = 5; I> 0; I --){
Key = new Integer (I). toString () + ". 0 ";
Map. put (key, key. toString ());
// Keys in Map are unique. If two records with the same key value are inserted,
// The record inserted later will overwrite the record inserted first
Map. put (key, key. toString () + "0 ");}
}
}
 
Public static void output (Map map ){
If (map! = Null ){
Object key = null;
Object value = null;
// Use the iterator to traverse the Map key.
Iterator it = map. keySet (). iterator ();
While (it. hasNext ()){
Key = it. next ();
Value = map. get (key );
System. out. println ("key:" + key + "; value:" + value );
}
// Or use the iterator to traverse the Map record Map. Entry
Map. Entry entry = null;
It = map. entrySet (). iterator ();
While (it. hasNext ()){
// A Map. Entry indicates a record.
Entry = (Map. Entry) it. next ();
// The key and value of the record can be obtained through the entry
// System. out. println ("key:" + entry. getKey () + "; value:" + entry. getValue ());
}
}
}
 
Public static boolean containsKey (Map map, Object key ){
If (map! = Null ){
Return map. containsKey (key );
}
Return false;
}
 
Public static boolean containsValue (Map map, Object value ){
If (map! = Null ){
Return map. containsValue (value );
}
Return false;
}
 
Public static void testHashMap (){
Map myMap = new HashMap ();
Init (myMap );
// The HashMap key can be null.
MyMap. put (null, "ddd ");
// The HashMap value can be null.
MyMap. put ("aaa", null );
Output (myMap );
} Www.2cto.com
 
Public static void testHashtable (){
Map myMap = new Hashtable ();
Init (myMap );
// The Hashtable key cannot be null.
// MyMap. put (null, "ddd ");
// The Hashtable value cannot be null.
// MyMap. put ("aaa", null );
Output (myMap );
}
 
Public static void testLinkedHashMap (){
Map myMap = new LinkedHashMap ();
Init (myMap );
// The LinkedHashMap key can be null.
MyMap. put (null, "ddd ");
MyMap. put (null, "aaa ");
// The LinkedHashMap value can be null.
MyMap. put ("aaa", null );
Output (myMap );
}
 
Public static void testTreeMap (){
Map myMap = new TreeMap ();
Init (myMap );
// The TreeMap key cannot be null.
// MyMap. put (null, "ddd ");
// The TreeMap value cannot be null.
// MyMap. put ("aaa", null );
Output (myMap );
}
 
Public static void main (String [] args ){
System. out. println ("using HashMap ");
TestMap. testHashMap ();
System. out. println ("using Hashtable ");
TestMap. testHashtable ();
System. out. println ("linkedlinkedhashmap ");
TestMap. testLinkedHashMap ();
System. out. println ("using TreeMap ");
TestMap. testTreeMap ();

Map myMap = new HashMap ();
TestMap. init (myMap );
System. out. println ("initialize a new Map: myMap ");
TestMap. output (myMap );
// Clear the Map
MyMap. clear ();
System. out. println ("is myMap empty after myMap is clear? "+ MyMap. isEmpty ());
TestMap. output (myMap );
MyMap. put ("aaa", "aaaa ");
MyMap. put ("bbb", "bbbb ");
// Determine whether a Map contains a key or a value
System. out. println ("myMap contains key aaa? "+ TestMap. containsKey (myMap," aaa "));
System. out. println ("Does myMap contain aaaa? "+ TestMap. containsValue (myMap," aaaa "));
// Delete records in Map based on the key
MyMap. remove ("aaa ");
System. out. println ("after the aaa key is deleted, myMap contains the aaa key? "+ TestMap. containsKey (myMap," aaa "));
// Obtain the number of Map records
System. out. println ("number of records contained in myMap:" + myMap. size ());
}
}
 
Output result:
Use HashMap
Key: null; value: ddd
Key: 3.0; value: 3.00
Key: aaa; value: null
Key: 4.0; value: 4.00
Key: 1.0; value: 1.00
Key: 5.0; value: 5.00
Key: 2.0; value: 2.00
Hashtable
Key: 4.0; value: 4.00
Key: 1.0; value: 1.00
Key: 3.0; value: 3.00
Key: 5.0; value: 5.00
Key: 2.0; value: 2.00
Use LinkedHashMap
Key: 5.0; value: 5.00
Key: 4.0; value: 4.00
Key: 3.0; value: 3.00
Key: 2.0; value: 2.00
Key: 1.0; value: 1.00
Key: null; value: aaa
Key: aaa; value: null
Use TreeMap
Key: 1.0; value: 1.00
Key: 2.0; value: 2.00
Key: 3.0; value: 3.00
Key: 4.0; value: 4.00
Key: 5.0; value: 5.00
Initialize a new Map: myMap
Key: 3.0; value: 3.00
Key: 4.0; value: 4.00
Key: 1.0; value: 1.00
Key: 5.0; value: 5.00
Key: 2.0; value: 2.00
After myMap is clear, is myMap empty? True
MyMap contains the key aaa? True
MyMap contains aaaa? True
After the key aaa is deleted, myMap contains the key aaa? False
MyMap records: 1

 
Source code analysis:
There are two methods to traverse Map:
(1) map's keySet () method obtains the key set, and then calls the iterator method of the key set to obtain the key iterator, so as to iteratively retrieve the key in the Map, obtain the value corresponding to the key using the get method, and then traverse the Map. The Code is as follows:
// Use the iterator to traverse the Map key.
Iterator it = map. keySet (). iterator ();
While (it. hasNext ()){
Key = it. next ();
Value = map. get (key );
System. out. println ("key:" + key + "; value:" + value );
}
(2) Use the Map entrySet method to obtain the set of records in the Map. Each object is a Map. entry object. Use its getKey method to obtain the record key and Its getValue method to obtain the record value. The Code is as follows:
// Or use the iterator to traverse the Map record Map. Entry
Map. Entry entry = null;
It = map. entrySet (). iterator ();
While (it. hasNext ()){
// A Map. Entry indicates a record.
Entry = (Map. Entry) it. next ();
// The key and value of the record can be obtained through the entry
// System. out. println ("key:" + entry. getKey () + "; value:" + entry. getValue ());

Related Article

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.