The difference between HashMap and TreeMap in Java

Source: Internet
Author: User

Let's start by describing what a map is. In the array we index the content by the array subscript, and in the map we index the object by object, the object to index is called key, and its corresponding object is called value. This is what we call a key-value pair.

HashMap quickly find its content through hashcode, and all elements in TreeMap remain in a fixed order, and if you need to get an ordered result you should use TREEMAP (the order of the elements in HashMap is not fixed).

HashMap non-thread-safe TreeMap non-thread safe

Thread Safety

In Java, thread safety generally manifests itself in two ways:

1, multiple thread access to the same Java instance (read and modify) does not interfere with each other, it is mainly embodied in the keyword synchronized. such as ArrayList and Vector,hashmap and Hashtable
(The latter has synchronized keywords before each method). If you are interator a list object and the other threads remove an element, the problem arises.

2. Each thread has its own field and is not shared across multiple threads. It is mainly embodied in the Java.lang. threadlocal class, without 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. The two mappings are equal if the two map sizes are equal, the same keys are included, and each key has the same value in both maps. The hash code of the map is the sum of the hash codes of the mapped elements, each of which is an implementation of the Map.entry interface. As a result, 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 key in an orderly order. The SortedMap interface provides an access method for the view (subset) of the image, including two endpoints. In addition to sorting is a key that works on a map, processing SortedMap is the same as dealing with SortedSet. The element added to the SortedMap implementation class must implement the comparable interface, otherwise you must give its constructor an implementation of the comparator interface. The TreeMap class is its only implementation.

2. Two general map implementations

HASHMAP: Based on hash table implementation. The key classes you add with HashMap explicitly define hashcode () and Equals () [can override Hashcode () and Equals ()], and to optimize the use of hashmap space, you can tune the initial capacity and load factor.

(1) HashMap (): Build an empty hash map image
(2) HashMap (map m): Build a hash map image and add all the mappings for 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 red-black tree. TreeMap has no tuning option because the tree is always in equilibrium.

(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 the mappings in the image tree S, and sorts with the same comparer as the ordered image s

3. Two general map performance

HashMap: Applies to inserting, deleting, and locating elements in a map.
Treemap: For traversing keys (key) in natural order or in a custom order.

4. Summary

HashMap is usually faster than treemap (the data structure of the tree and hash table), it is recommended to use HashMap, and TreeMap is used when the map needs to be sorted.

Import Java.util.HashMap;Import java.util.Hashtable;Import Java.util.Iterator;Import Java.util.Map;Import Java.util.TreeMap; PublicClassHashmaps {publicStaticvoid 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", Span class= "hljs-string" > "BBB"); Tmp.put ( "C",  "CCC"), Tmp.put ( "D", Span class= "hljs-string" > "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 DDMap.Get (Key)is:bbbmap. 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 well sequenced.

The following is the subject of this article. Let me give you an example of how to use HashMap:

Import java.util.*;PublicClassEXP1 {PublicStaticvoidMainString[] 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);}}      

Using get () to get value in HashMap, inserting Value,containskey () through put () is used to verify that the object already exists. It can be seen that, compared with ArrayList's operation, HashMap is not very different from other aspects except by indexing its contents by key.

As described earlier, HashMap is based on hashcode, there is a hashcode () method in the superclass object of all objects, but it does not apply to all cases like the Equals method, so that we need to rewrite our own hashcode () method. Here's an example:

Import java.util.*;PublicClassEXP2 {PublicStaticvoidMainString[] 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, element is used to index the object figureout, which means that element is key,figureout as value. A floating-point number is randomly generated in figureout, and if it is larger than 0.5, print "ok!", otherwise print "impossible!". Then see how the Figureout results for Element (3).

It turns out that no matter how many times you run, the result is "not found". This means that the index element (3) is not in HashMap. How is that possible?

The reason for this is that the Hashcode method of element inherits from object, whereas the hashcode returned by the Hashcode method in object corresponds to the current address, that is, for different objects, even if their contents are identical, The value returned with Hashcode () will also be different. This is in fact contrary to our intentions. Because we want to use the same Content Object index to get the same target object when we are using HashMap, it is necessary for hashcode () to return the same value at this time. In the example above, 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 they have different addresses in memory. So it is natural that the above procedure is not going to be the result of our vision. The following changes are made to the element class:

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 covers the hashcode () and Equals () methods in object. Overwrite hashcode () so that it returns as the value of number as hashcode, so that their hashcode are the same for objects of the same content. overriding Equals () is to make the result meaningful when HASHMAP determines whether two keys are equal (for overriding equals (), you can refer to my other article, "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 will have to rewrite it in its hashcode ().

There are two principles for rewriting hashcode ():
[List=1]

You do not have to produce a unique hashcode for each different object, as long as your Hashcode method enables get () to get the contents of the put () to be put in. That is, "not a principle".

The algorithm that generates hashcode as far as possible to make the value of hashcode scattered some, not many hashcode are concentrated in one range, this is advantageous to improve hashmap performance. That is, the principle of decentralization. As for the specific reasons for the second principle, interested persons can refer to Bruce Eckel's "Thinking in Java", where there is an introduction to the principle of hashmap internal implementation, here will not repeat.

With these two principles in hand, you will be able to write your own program with good HashMap. I don't know. No, there are three methods available in Java.lang.Object: Clone (), Equals (), and hashcode () are typical, but in many cases are not applicable, they are simply the object's address to derive results. This requires us to rewrite them in our own programs, and in fact the Java class Library has rewritten hundreds of thousands of such methods. Using object-oriented polymorphism-overlay, Java's designers have built the Java architecture gracefully, and have also embodied the Java is a pure OOP language features.

The difference between HashMap and TreeMap in Java

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.