Usage of HashMap in Java

Source: Internet
Author: User

Highlights HashMap. 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. Examples are provided below.

Let's see what the difference is between HashMap and TreeMap. 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).

 Import Java.util.Map;    Import Java.util.HashMap;    Import Java.util.Set;    Import Java.util.HashSet;    Import Java.util.Iterator;    Import java.util.Hashtable;    Import Java.util.TreeMap;                            Class Hashmaps {public static void main (string[] args) {Map map=new HashMap ();                Map.put ("A", "AAA");                Map.put ("B", "BBB");                Map.put ("C", "CCC");                               Map.put ("D", "ddd");                            Iterator Iterator = Map.keyset (). Iterator ();                 while (Iterator.hasnext ()) {Object key = Iterator.next ();                System.out.println ("Map.get (Key) is:" +map.get (key));                            } Hashtable tab=new Hashtable ();                Tab.put ("A", "AAA");                Tab.put ("B", "BBB");                Tab.put ("C", "CCC");     Tab.put ("D", "ddd");           Iterator 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 tmp=new TreeMap ();                Tmp.put ("A", "AAA");                Tmp.put ("B", "BBB");                Tmp.put ("C", "CCC");                Tmp.put ("D", "ddd");                Iterator iterator_2 = Tmp.keyset (). Iterator ();                 while (Iterator_2.hasnext ()) {Object key = Iterator_2.next ();                System.out.println ("Tmp.get (Key) is:" +tmp.get (key));     }                                                           }             }

After the execution, sure enough (HashMap is no order, and TreeMap is in order!!) )

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

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);                   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.

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

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, 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 (5).

It turns out that no matter how many times you run, the result is "not found". This means that the index element (5) 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 element test=new element (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 ():

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.

Usage of HashMap in Java

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.