java-Foundation-treemap and HashMap

Source: Internet
Author: User

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, and there is no 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.

hashmap: Based on hash table implementation. The key classes that are added with HashMap require a clear definition of hashcode ()  and equals ()  [can override Hashcode () and Equals ()]  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 ( Span class= "Hljs-number" >3 ) HashMap (int initialcapacity): Build an empty hash map image with a specific capacity (4 ) HashMap (int initialcapacity, float loadfactor): Constructs an empty hash map like TREEMAP with a specific capacity and load factor: Based on the red-black tree implementation. TreeMap has no tuning option because the tree is always in equilibrium. (1 ) TreeMap (): Build an empty image tree (2 ) TreeMap (Map m): Build an image tree and add all the elements in the image m ( 3 ) TreeMap (Comparator C): Build an image tree and sort the keywords using a specific comparer (4 ) TreeMap (sortedmap s): Building an image tree , add all the mappings in the image tree S and sort   with the same comparer as the ordered image s 

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

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, St Ring> (); 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, 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)); } } }

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.*; Public classEXP1 { Public Static void Main(string[] args) {HashMap h1=NewHashMap (); Random r1=NewRandom (); for(intI=0;i< +; i++) {Integer t=NewInteger (R1.nextint ( -));if(H1.containskey (t)) ((Ctime) H1.Get(t)). count++;ElseH1.put (T,NewCtime ()); } System. out. println (H1); }} class ctime{intCount=1; PublicStringtoString(){returnInteger.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.

Import java.util.*; Public classEXP2 { Public Static void Main(string[] args) {HashMap h2=NewHashMap (); for(intI=0;i<Ten; i++) H2.put (NewElement (i),NewFigureout ()); System. out. println ("H2:"); System. out. println ("Get The result for Element:"); Element test=NewElement (5);if(H2.containskey (test)) System. out. println (Figureout) H2.Get(test));ElseSystem. out. println ("Not Found"); }} class element{intNumber Public Element(intn) {number=n;}} Class figureout{Random r=NewRandom (); Boolean possible=r.nextdouble () >0.5; PublicStringtoString(){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).

The

Results show 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, which means that 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
face element class changes are as follows:

class element{int  number; Span class= "Hljs-keyword" >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.

java-Foundation-treemap and HashMap

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.