Deep understanding of the difference between HashMap and TreeMap in Java _java

Source: Internet
Author: User

First, let's introduce what map is. In the array we index the contents by an array, and in the map we index the object by object, and the object used for indexing is called key, and its corresponding object is called value. This is what we normally say as key-value pairs.

HashMap the contents of the hashcode by a quick lookup, and treemap all the elements are in a certain order, if you need to get an orderly result you should use TreeMap (HashMap in the order of the elements are not fixed).
HashMap non-thread-safe TreeMap non-thread-safe

Thread Safety
In Java, thread safety is generally embodied in two aspects:
1. Multiple thread access to the same Java instance (read and modify) will not interfere with each other, it is mainly embodied in the keyword synchronized. such as ArrayList and Vector,hashmap and Hashtable
(the latter has a synchronized keyword before each method). If you interator a list object, the other thread removes an element, and the problem arises.

2. Each thread has its own field, and it is not shared among multiple threads. It is mainly embodied in the Java.lang.ThreadLocal class, not Java keyword support, such as static, transient.
1.ABSTRACTMAP abstract class and SortedMap interface
Abstractmap abstract class: (HashMap inheritance Abstractmap) overrides the Equals () and Hashcode () methods to ensure that two equality mappings return the same hash code. If two mapping sizes are equal, contain the same keys, and each key corresponds to the same values in both mappings, the mappings are equal. The mapped hash code is the sum of the mapped element hash codes, where each element is an implementation of the Map.entry interface. Therefore, two equality mappings report the same hash code regardless of the internal order of the mappings.
SortedMap Interface: (TreeMap inherits from SortedMap) it is used to keep the order of the keys. The SortedMap interface is a view (subset) of the image, and includes two endpoints that provide access methods. In addition to the sort that is acting on the mapped key, processing sortedmap and handling SortedSet is the same. Elements added to the SortedMap implementation class must implement the comparable interface, otherwise you must provide an implementation of the comparator interface to its constructors. The TreeMap class is its only implementation.

2. Two general map implementations
HASHMAP: Based on hash table implementations. Hashcode () and Equals () can be overridden hashcode () and Equals () to optimize the use of the HashMap space, and you can tune the initial capacity and load factors by using the key class added by the hashmap requirement.
(1) HashMap (): Build an empty hash map like
(2) HashMap (map m): Construct a hash map image, and add all mappings of the images m
(3) HashMap (int initialcapacity): Constructs an empty hash map image with a specific capacity
(4) HashMap (int initialcapacity, float loadfactor): Constructs an empty hash map image with a specific capacity and load factor
TREEMAP: Based on the red-black tree implementation. TreeMap has no tuning options because the tree is always in a balanced state.
(1) TreeMap (): Building an empty image tree
(2) TreeMap (Map m): Build an image tree and add all elements in image m
(3) TreeMap (Comparator C): Build an image tree and sort the keywords using a specific comparer
(4) TreeMap (SortedMap s): Constructs an image tree, adds all mappings in the image tree S, and sorts using the same comparer as the ordered image s

3. Two general map performance
HashMap: Applies to inserting, deleting, and positioning elements in a map.
Treemap: is suitable for traversing key (key) in natural order or custom order.

4. Summary
HashMap are usually faster than treemap (the data structure of a tree and hash table), and it is recommended that you use HashMap more often than treemap when you need to sort the map.

Copy Code code as follows:

Import Java.util.HashMap;
Import java.util.Hashtable;
Import Java.util.Iterator;
Import Java.util.Map;
Import Java.util.TreeMap;
public class Hashmaps {
public static void Main (string[] args) {
map<string, string> map = new hashmap<string, string> ();
Map.put ("A", "AAA");
Map.put ("B", "BBB");
Map.put ("C", "CCC");
Map.put ("D", "ddd");
Iterator<string> iterator = Map.keyset (). iterator ();
while (Iterator.hasnext ()) {
Object key = Iterator.next ();
System.out.println ("Map.get (Key) is:" + map.get (key));
}
Define Hashtable, which is used to test
hashtable<string, string> tab = new hashtable<string, string> ();
Tab.put ("A", "AAA");
Tab.put ("B", "BBB");
Tab.put ("C", "CCC");
Tab.put ("D", "ddd");
iterator<string> iterator_1 = Tab.keyset (). iterator ();
while (Iterator_1.hasnext ()) {
Object key = Iterator_1.next ();
System.out.println ("Tab.get (Key) is:" + tab.get (key));
}
treemap<string, string> tmp = new treemap<string, string> ();
Tmp.put ("A", "AAA");
Tmp.put ("B", "BBB");
Tmp.put ("C", "CCC");
Tmp.put ("D", "CDC");
iterator<string> iterator_2 = Tmp.keyset (). iterator ();
while (Iterator_2.hasnext ()) {
Object key = Iterator_2.next ();
System.out.println ("Tmp.get (Key) is:" + tmp.get (key));
}
}
}

The results of the operation are as follows:
Map.get (key) is:D DD
Map.get (Key) is:bbb
Map.get (Key) IS:CCC
Map.get (Key) is:aaa
Tab.get (Key) is:bbb
Tab.get (Key) is:aaa
Tab.get (key) is:D DD
Tab.get (Key) IS:CCC
Tmp.get (Key) is:aaa
Tmp.get (Key) is:bbb
Tmp.get (Key) IS:CCC
Tmp.get (Key) IS:CDC
The results of the hashmap are not sorted, and the results of the TREEMAP output are arranged in order.
The following is the subject of this article. Let me give you an example of how to use HashMap:
Copy Code code as follows:

Import java.util.*;
public class Exp1 {
public static void Main (string[] args) {
HashMap h1=new HashMap ();
Random r1=new Random ();
for (int i=0;i<1000;i++) {
Integer t=new Integer (R1.nextint (20));
if (H1.containskey (t))
((Ctime) h1.get (t)). count++;
Else
H1.put (T, new Ctime ());
}
SYSTEM.OUT.PRINTLN (H1);
}
}
Class ctime{
int count=1;
Public String toString () {
Return integer.tostring (count);
}
}

The value is obtained by getting () in the HashMap, and the Value,containskey () is inserted by the put () to verify that the object already exists. It can be seen that, compared with the ArrayList operation, HashMap in addition to the key index its content, other aspects of the difference is not big.
As described earlier, HashMap is based on Hashcode and has a hashcode () method in the superclass object of all objects, but like the Equals method, it does not apply to all situations, so we need to rewrite our own hashcode () method. Here's an example:
Copy Code code as follows:

Import java.util.*;
public class Exp2 {
public static void Main (string[] args) {
HashMap h2=new HashMap ();
for (int i=0;i<10;i++)
H2.put (New Element (i), New Figureout ());
System.out.println ("H2:");
System.out.println ("Get the result for Element:");
Element test=new Element (5);
if (H2.containskey (test))
System.out.println ((figureout) h2.get (test));
Else
System.out.println ("not Found");
}
}
Class element{
int number;
public Element (int n) {
Number=n;
}
}
Class figureout{
Random r=new Random ();
Boolean possible=r.nextdouble () >0.5;
Public String toString () {
if (possible)
return "ok!";
Else
return "impossible!";
}
}

In this example, the element is used to index the object figureout, or the element is key,figureout to value. Randomly generates a floating-point number in figureout, if it is larger than 0.5, print "ok!", otherwise print "impossible!". Then see how the Figureout result of element (3) corresponds.

It turns out that no matter how many times you run, the results are "not found." This means that the index element (3) is not in HashMap. How is that possible?
The reason is slowly: the Hashcode method of the element inherits from object, and the Hashcode returned by the Hashcode method in object corresponds to the current address, which means that for different objects, even if their contents are exactly the same, The value returned with Hashcode () will also be different. This is actually against our intention. Because when we use HASHMAP, we want to get the same target object with the object index of the same content, which requires hashcode () to return the same value at this time. In the above example, we expect the new Element (i) (i=5) to be the same as elementtest=newelement (5), which is actually two different objects, although their contents are the same, but their addresses in memory are different. It is therefore natural that the procedures above do not get the results we envisage. The following changes to the element class are as follows:
Copy Code code as follows:

Class element{
int number;
public Element (int n) {
Number=n;
}
public int hashcode () {
return number;
}
public boolean equals (Object o) {
Return (o instanceof Element) && (number== ((Element) O). number);
}
}

Here the element overrides the Hashcode () and Equals () methods in object. Overwrite Hashcode () to return the value of number as hashcode, so that their hashcode is the same for objects of the same content. overriding Equals () is to make the result meaningful when HASHMAP determines whether two keys are equal (the content of overriding equals () can be referenced in my other article, "Rewrite methods in the object class"). The results of the modified program run as follows:
H2:
Get the result for Element:
impossible!
Remember: If you want to use HashMap effectively, you must rewrite it in its hashcode ().
There are also two overriding principles of hashcode ():
[List=1]
You don't have to have a single hashcode for every different object, as long as your Hashcode method allows get () to be put () into the content. That is, "not a principle".

Generate Hashcode algorithm to make the value of hashcode to disperse some, not many hashcode are concentrated in a range, which is conducive to improving the performance of HashMap. Namely "the principle of decentralization". As for the specific reasons for the second principle, interested people can refer to Bruce Eckel's "Thinking in Java", where there is an introduction to the principle of hashmap internal implementation, here is not to repeat.
With these two principles in hand, you can write your own program with good HashMap. I don't know if you're aware of it. The three methods provided in Java.lang.Object: Clone (), Equals () and hashcode (), although typical but not applicable in many cases, are simply the result of an object's address. This requires us to rewrite them in our own programs, but in fact the Java class Library has rewritten hundreds of thousands of such methods. With object-oriented polymorphism-overlay, Java designers have built the Java architecture gracefully, and have also shown that Java is a pure OOP language feature.

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.