Notes for using hash to write equals

Source: Internet
Author: User

When using hashmap, map. containskey (key)
I want to call my equals method, but map is not willing to call my equals

It was solved later because hashmap uses the hash algorithm, and equals is quite special.
In addition to equals, you also need to write

Public int hashcode ()...{
// Todo auto-generated method stub
Return key1.hashcode () + key2.hashcode ();
}

 

Returns the hashcode of the value required in equals.

Below is an instance

Public class keys implements serializable ...{
String key1;
String key2;

/***//**
* @ Return returns the key1.
*/
Public String getkey1 ()...{
Return key1;
}
/***//**
* @ Param key1 the key1 to set.
*/
Public void setkey1 (string key1 )...{
This. key1 = key1;
}
/***//**
* @ Return returns the key2.
*/
Public String getkey2 ()...{
Return key2;
}
/***//**
* @ Param key2 the key2 to set.
*/
Public void setkey2 (string key2 )...{
This. key2 = key2;
}
 
Public Boolean equals (Object obkey)
...{
Keys key = (KEYS) obkey;
If (Key = NULL | key. getkey1 () = NULL | key. getkey2 () = NULL)
Return false;
If (key. getkey1 (). Equals (this. key1) & Key. getkey2 (). Equals (this. key2 ))
Return true;
Return false;
 

}
 
Public String tostring ()
...{
String M = "key1:" + this. key1 + "key2:" + this. key2;
Return m;
}
/** // * (Non-javadoc)
* @ See java. Lang. Object # hashcode ()
*/
Public int hashcode ()...{
// Todo auto-generated method stub
Return key1.hashcode () + key2.hashcode ();
}
}

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.