Does the hashcode method need to be rewritten after the equals method of the object is rewritten?

Source: Internet
Author: User
Tags cairo

First, let's talk about the recommended situation: for example, when your object wants to be put into a set or a map key (non-Hash set and map, such as treeset and treemap ), then you must override the equals () method to ensure uniqueness. Of course, in this case, you do not want to rewrite the hashcode () method, and there is no error. However, for a good programming style, you should rewrite the hashcode () method while rewriting the equals () method.

Then let's talk about the situation where hashcode () must be rewritten:
If your object is to be placed in a Hash Storage set (such as hashset and hashset) or as a key of a hash map (such as hashmap and linkedhashmap, while rewriting the equals () method, you must override the hashcode () method.

Here I want to explain why Sun designers need to design the hashcode method. Maybe you should know when to rewrite it.
The data structure has a data structure that exists to improve the search efficiency-the hash list. The hash list is actually a promotion of the General array concept, because it can directly address the array, therefore, we can access any element of the array in O (1) Time. Thinking has a simple implementation of hashmap in Java. Let's take a look at it and you will understand:

 

  1. //: Containers/simplehashmap. Java

  2. // A demonstration hashed map.

  3. Import java. util .*;

  4. Import net. mindview. util .*;

  5. Public class simplehashmap <K, V> extends abstractmap <K, V> {

  6. // Choose a prime number for the hash table

  7. // Size, to achieve a uniform distribution:

  8. Static final int size = 997;

  9. // You can't have a physical array of generics,

  10. // But you can upcast to one:

  11. @ Suppresswarnings ("unchecked ")

  12. Counter list <mapentry <K, V> [] buckets =

  13. New shortlist [size]; // each item in the list array is a list, and the array subscript is the return value of the hashcode method, which is obtained through the hash function, which is equivalent to the keyword of the hash list, it also represents the keywords of each object. (A New Generic Array cannot be displayed, but you can reference A New Generic Array. If necessary, you can convert an ordinary array to a generic array ).

  14. Public v put (K key, V value) {// put this key pair value into hashmap.

  15. V oldvalue = NULL;

  16. Int Index = math. ABS (key. hashcode () % size; // here, a keyword is obtained through processing the return value of hashcode by the hash function. It represents the position of the object in the array and is both an array subscript.

  17. If (buckets [Index] = NULL)

  18. Buckets [Index] = new partition list <mapentry <K, V> (); // if this is the first time the array subscript is hashed, a new partition list is generated, you can see that mapentry <K, V> keys and values are saved in it.

  19. Your list <mapentry <K, V> bucket = buckets [Index]; // assign the value of your list to a bucket. Then, you can operate on this bucket directly.

  20. Mapentry <K, V> pair = new mapentry <K, V> (Key, value );

  21. Boolean found = false;

  22. Listiterator <mapentry <K, V> it = bucket. listiterator ();

  23. While (it. hasnext ()){

  24. Mapentry <K, V> ipair = it. Next ();

  25. If (ipair. getkey (). Equals (key) {// if the same key value already exists, update the value.

  26. Oldvalue = ipair. getvalue ();

  27. It. Set (pair); // replace old with new

  28. Found = true;

  29. Break;

  30. }

  31. }

  32. If (! Found)

  33. Buckets [Index]. Add (pair); // if it is a new key value, directly add it to this sort list.

  34. Return oldvalue;

  35. }

  36. Public v get (Object key) {// see how hashmap uses the hashcode method to quickly locate the key value.

  37. Int Index = math. ABS (key. hashcode () % size; [color = Red] // generates an array subscript in the same way as the put method, because it is stored in this place when I save it, then, access buckets [Index] directly. [/Color]

  38. If (buckets [Index] = NULL) return NULL; // directly access the list of objects under the array. If it is null, return.

  39. For (mapentry <K, V> ipair: buckets [Index]) // Why should we use the sorted list? Because the hash code generated by the hashcode method cannot completely determine an object, that is to say, it will "collide" with other objects, that is, hash to the same Array subscript. The way to solve this problem is to define a list to save them, but in this list, we must ensure that the equals method can be used to determine the identity of an object. That is why many people say that hashcode () is equal, equals () is not necessarily equal, and equals () is equal to two objects, hashcode () must be equal. Therefore, linear search is directly performed on the sorted list.

  40. If (ipair. getkey (). Equals (key ))

  41. Return ipair. getvalue ();

  42. Return NULL;

  43. }

  44. Public set <map. Entry <K, V> entryset (){

  45. Set <map. Entry <K, V> set = new hashset <map. Entry <K, V> ();

  46. For (catalog list <mapentry <K, V> Bucket: buckets ){

  47. If (bucket = NULL) continue;

  48. For (mapentry <K, V> mpair: bucket)

  49. Set. Add (mpair );

  50. }

  51. Return set;

  52. }

  53. Public static void main (string [] ARGs ){

  54. Simplehashmap <string, string> M =

  55. New simplehashmap <string, string> ();

  56. M. putall (countries. capitals (25 ));

  57. System. Out. println (m );

  58. System. Out. println (M. Get ("Eritrea "));

  59. System. Out. println (M. entryset ());

  60. }

  61. }/* Output:

  62. {Cameroon = Yaounde, Congo = Brazzaville, Chad = N' Djamena, Cote d' ivoir (Ivory Coast) = California, Central African Republic = Bangui, Guinea = Conakry, Botswana = Gaberone, bissau = Bissau, Egypt = Cairo, Angola = Luanda, Burkina Faso = California, Eritrea = Asmara, the Gambia = Banjul, Kenya = Nairobi, Gabon = Libreville, Cape Verde = Praia, algeria = Algiers, Comoros = Moroni, Equatorial Guinea = Malabo, Burundi = Beijing, Benin = Porto-Novo, Bulgaria = Sofia, Ghana = Accra, region = dijiboti, region = Addis Ababa}

  63. Asmara

  64. [Cameroon = Yaounde, Congo = Brazzaville, Chad = N' Djamena, Cote d' ivoir (Ivory Coast) = California, Central African Republic = Bangui, Guinea = Conakry, Botswana = Gaberone, bissau = Bissau, Egypt = Cairo, Angola = Luanda, Burkina Faso = California, Eritrea = Asmara, the Gambia = Banjul, Kenya = Nairobi, Gabon = Libreville, Cape Verde = Praia, algeria = Algiers, Comoros = Moroni, Equatorial Guinea = Malabo, Burundi = Beijing, Benin = Porto-Novo, Bulgaria = Sofia, Ghana = Accra, region = dijiboti, region = Addis Ababa


How? Now we should know the role of the hashcode method, which is used to improve efficiency. There is a saying: Hashing for speed. Because the hash set and map are based on the hashcode method to find objects, you must overwrite the hashcode method when using these classes, instead of the hash set and map, for example, treeset and treemap, they only need the equals method to uniquely identify the object. In this case, it must be clear.



Does the hashcode method need to be rewritten after the equals method of the object is rewritten?

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.