Java custom type as the key value in HashMap (pair<v,k> for example)

Source: Internet
Author: User
Tags function prototype

Because it is a custom type, custom overrides are required for the Equals () function and the hashcode () function in HashMap.

Otherwise the content of the same object corresponding to the hashcode will be different, unable to play the normal function of the algorithm, covering the Equals function, should be equivalent to C + + overloaded = = operator to ensure that the equality can be judged. Except that Java does not have a custom overloaded operator, which requires a function overlay.

The function prototype of equals is the Boolean equals (Object O); The function prototype of hashcode is int hashcode ();

Look at the code first:

ImportJava.util.*;classPair<v,k>{V first;    K second;  PublicPair () {first =NULL; second =NULL;}  PublicPair (V f,k s) { first=F; Second=s; }//Public Boolean equals (Object o) {//if (! ( o instanceof Pair))//        {//return false;//        }//pair<v,k> pn = (pair<v,k>) o;//return Pn.first.equals (first) && pn.second.equals (second);//    }//public int Hashcode () {//return First.hashcode () + Second.hashcode ();//    }} Public classMain { Public Static voidMain (string[] args) {Pair<String,String> p =NewPair<> ("A", "B"); Pair<String,String> q =NewPair<> ("A", "B");        System.out.println (P.equals (q)); System.out.println (P.hashcode ()+ " " +Q.hashcode ()); Map<Pair<String,String>,Integer> map =NewHashMap (); Map.put (P,1);        System.out.println (Map.containskey (q)); Map.put (q,2);  for(pair<string,string>Key:map.keySet ())        {System.out.println (Map.get (key)); }    }}

This code the overloaded two functions to comment out, and then determine the value of the same two pair object P and Q are equal, and output their hashcode, and put P into the established HashMap, with Q to determine whether p exists, then put Q into, and traverse the values of the map. The answer is:

False
2018699554 1311053135
False
1
2

And then:

ImportJava.util.*;classPair<v,k>{V first;    K second;  PublicPair () {first =NULL; second =NULL;}  PublicPair (V f,k s) { first=F; Second=s; }     Public Booleanequals (Object o) {if(! (OinstanceofPair)) {            return false; } Pair<V,K> pn = (pair<v,k>) O; returnPn.first.equals (first) &&Pn.second.equals (second); }     Public inthashcode () {returnFirst.hashcode () +Second.hashcode (); }} Public classMain { Public Static voidMain (string[] args) {Pair<String,String> p =NewPair<> ("A", "B"); Pair<String,String> q =NewPair<> ("A", "B");        System.out.println (P.equals (q)); System.out.println (P.hashcode ()+ " " +Q.hashcode ()); Map<Pair<String,String>,Integer> map =NewHashMap (); Map.put (P,1);        System.out.println (Map.containskey (q)); Map.put (q,2);  for(pair<string,string>Key:map.keySet ())        {System.out.println (Map.get (key)); }    }}

Then the result of removing the note is:

True
195 195
True
2

Although there is no reason to say that the hashcode overload here, but at least the same value of two objects their hashcode is the same, so that in HashMap the first level to determine whether Hashcode is the same, and then traverse to determine whether there are values of the same element, You can determine if a key value is included, update the value of the key, and so on.

Also note that the override of equals, the argument list cannot be changed to pair p because it is for pair, so it is only overloaded and does not overwrite.

Java custom type as the key value in HashMap (pair<v,k> for example)

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.