Reprinted HASHMAP usage Summary

Source: Internet
Author: User

 

HashMap usage Summary

This article focuses on HashMap. First, we will introduce what Map is. In the array, We index its content through the array subscript, while in the Map, we index the object through the object. The object to be indexed is called the key, the corresponding object is value. An example is provided below.

Let's take a look at the differences between HashMap and TreeMap. HashMap uses hashcode to quickly search its content, while all elements in TreeMap maintain a fixed order, if you need to get an ordered result, you should use TreeMap (the arrangement order of 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 ));
}


}

}
This is true after execution (hashmap has no order, and treemap is arranged in order !!)

 

The following is the topic of this article. The following example shows 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 (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 );
}
}

In HashMap, get () is used to obtain the value, put () is used to insert the value, and ContainsKey () is used to check whether the object already exists. It can be seen that, compared with the ArrayList operation, HashMap not only indexes its content through the key, but also has little difference in other aspects.

 

As mentioned above, HashMap is based on HashCode. There is a HashCode () method in the super-class Object of all objects, but it is the same as the equals method and cannot apply to all situations, in this way, we need to rewrite our own HashCode () method. The following is 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, the Element is used to index the object Figureout, that is, the Element is the key, and the Figureout is the value. A floating point number is randomly generated in Figureout. If it is larger than 0.5, print "OK! ", Otherwise print" Impossible! ". Then, view the Figureout result corresponding to Element (3.

The result shows that no matter how many times you run it, the result is "Not found ". That is to say, the index Element (3) is not in HashMap. How is this possible?

The reason is that the HashCode method of the Element inherits from the Object, while the HashCode returned by the HashCode method in the Object corresponds to the current address, that is, for different objects, even if their content is identical, the values returned with HashCode () are also different. This actually violates our intention. Because when we use HashMap, we want to use the same content of the object index to get the same target object, which requires HashCode () to return the same value at this time. In the preceding example, we expect that the new Element (I) (I = 5) and Element test = new Element (5) are the same, but actually they are two different objects, although they share the same content, they have different addresses in the memory. So naturally, the above program won't get the result we imagined. The following changes 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, element overwrites the hashcode () and equals () methods in the object. Overwrite hashcode () so that it returns the value of number as hashcode, so that their hashcode is the same for objects with the same content. Overwrite equals () is used to make the result meaningful when hashmap judges whether two keys are equal (related to rewriting equals () for more information, see my another article "re-compile methods in the object class". The modified program running result is as follows:

H2:
Get the result for element:
Impossible!

Remember: If you want to use hashmap effectively, you must overwrite it in its hashcode ().

There are two principles for rewriting hashcode:

  1. You don't have to generate a unique hashcode for each different object, as long as your hashcode method enables get () to get the content put in put. That is, "Not one principle ".
  2. The hashcode generation algorithm tries its best to make the hashcode values more scattered, rather than a lot of hashcode is concentrated in a range, which is conducive to improving the performance of hashmap. That is, the "Decentralization principle ".

For the specific reasons for the second principle, if you are interested, refer to Bruce Eckel's thinking in Java, where I will introduce the internal implementation principles of hashmap. I will not go into details here.

With these two principles, you can use hashmap to write your own program. I don't know if you have noticed this. java. lang. although clone (), equals (), and hashcode () methods are typical, they are not applicable in many cases, they are simply obtained by the object address. This requires us to rewrite them in our own programs. In fact, the Java class library has also rewritten thousands of such methods. With object-oriented polymorphism-overwrite, Java designers elegantly construct the Java structure and reflect the characteristics of Java as a pure OOP language.

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.