Why rewrite the Equals () method in Java to override the Hashcode () method?

Source: Internet
Author: User

The public boolean equals (Object obj) in object objects, and the method returns true for any non-null reference value x and Y, when and only if X and Y refer to the same object;
Note: When this method is overridden, it is often necessary to override the Hashcode method to maintain the general contract of the Hashcode method, which declares that the equality object must have an equal hash code. As follows:
(1) when Obj1.equals (OBJ2) is true, obj1.hashcode () = = Obj2.hashcode () must be true
(2) when obj1.hashcode () = = Obj2.hashcode () is False, Obj1.equals (OBJ2) must be false
If you do not override Equals, then the comparison will be whether the object's reference points to the same memory address, which is overridden to compare the value of two objects for equality. In particular, the use of equals to compare eight large packaging objects
(such as int,float, etc.) and the string class (because the class has overridden the Equals and Hashcode methods) object, the default comparison is the value, which is the reference address of the comparison when comparing other custom objects
Hashcode is a fast access for hashing data, such as using the Hashset/hashmap/hashtable class to store data, based on the hashcode value of the stored object to determine whether the same.
So if we rewrite the euqals for an object, it means that as long as the values of the member variables of the object are equal then Euqals equals true, but does not rewrite hashcode, then we are new to the object,
When the original object. Equals (New Object) equals True, the hashcode of the two is not the same, resulting in an inconsistent understanding, such as when storing a hash collection (such as set Class), will store two values of the same object,
Cause confusion, therefore, it is also necessary to rewrite hashcode ()
To illustrate:

[Java]View Plaincopy
  1. Import java.util.*;
  2. Public class HelloWorld {
  3. public static void Main (string[] args) {
  4. /* 
  5. Collection C = new HashSet ();
  6. C.add ("Hello");
  7. C.add (New Name ("F1", "L1"));
  8. C.add (New Integer (100));
  9. C.remove ("Hello");
  10. C.remove (New Integer (100));
  11. System.out.println (C.remove (New Name ("F1", "L1"));
  12. */
  13. Name n1 = new name ("01");
  14. Name N2 = new name ("01");
  15. Collection C = new HashSet ();
  16. C.add (N1);
  17. System.out.println ("------------");
  18. C.add (N2);
  19. System.out.println ("------------");
  20. System.out.println (N1.equals (N2));
  21. System.out.println ("------------");
  22. System.out.println (N1.hashcode ());
  23. System.out.println (N2.hashcode ());
  24. System.out.println (c);
  25. }
  26. }
  27. Class Name {
  28. private String ID;
  29. Public Name (String id) {
  30. this.id = ID;
  31. }
  32. Public String toString () {
  33. return this.id;
  34. }
  35. public boolean equals (Object obj) {
  36. if (obj instanceof Name) {
  37. Name name = (name) obj;
  38. System.out.println ("equal" + name.id);
  39. return (Id.equals (name.id));
  40. }
  41. return super.equals (obj);
  42. }
  43. public int hashcode () {
  44. Name name = (name) this ;
  45. System.out.println ("Hash" + name.id);
  46. return Id.hashcode ();
  47. }
  48. }


For this program analysis, the first time you add, the Hashcode () method is called, the hashcode is stored in the object, the second time, and then the hashcode is compared. Hashcode is also used only for hashset/hashmap/hashtable classes to store data, so it is used for comparisons and needs to be rewritten

Summary, the custom class to override the Equals method for equivalent comparison, the custom class to override the CompareTo method for comparison of different object sizes, overriding the Hashcode method in order to compare the data to the Hashset/hashmap/hashtable class

In general, if you want to put objects of a class into a container, you typically override the Equals () method for them to compare the address value to the content value. In particular, if you want to put the object of your class in a hash, rewrite the Hashcode () method, and then override the CompareTo () method to put it in an ordered container.
Equals () equal to two objects, hashcode () must be equal;
Equals () is not equal to two objects, but does not prove that their hashcode () are unequal. In other words, the Equals () method is not equal to two objects, and hashcode () may be equal. (My understanding is that the hash code was generated when the conflict was created).
In turn: Hashcode () can not be equal to the introduction of equals () also unequal; Hashcode () Equality, equals () may be equal or may not vary

Hash

Let's start with a picture to see what a hash is.

Hash is the meaning of hashing, that is, the arbitrary length of the input, through the hash algorithm to transform into a fixed-length output, the output is the hash value. There are several key conclusions about the hash value:

1, if the hash table exists and hashes the original input K equal records, then K must be in the F (K) storage location

2, the different keywords after hashing algorithm transformation may get the same hash address, this phenomenon is called collision

3, If two hash values are different (if the same hash algorithm), then these two hash values corresponding to the original input must be different

Hashcode

Then say what is hashcode and summarize several key points:

1, the existence of hashcode is mainly for the purpose of finding the shortcut, Hashcode is used in the hash storage structure to determine the storage address of the object

2. If two objects equals equal, then the hashcode of the two objects must be the same

3, if the object's Equals method is overridden, then the object's Hashcode method is also rewritten as much as possible

4, if the hashcode of two objects is the same, does not mean that two objects are the same, can only show that the two objects in the hash storage structure, stored in the same location

What's the use of hashcode?

Back to the most critical question, what's the use of hashcode? Let me give you an example:

1, assume that in memory 0 1 2 3 4 5 6 7 8 of these 8 locations, if I have a field called ID, then I would like to store this field in one of the above 8 locations, if not hashcode and arbitrarily stored, then when the search will need to go to 8 locations to find each

2, the use of hashcode efficiency will be much faster, the ID of the hashcode%8, and then the ID stored in the remainder of the location, and then each time you find the class can be the ID of the hashcode%8 to find the remainder directly to the location of the store

3, if the ID of the hashcode%8 figure out the location itself already has data, how to do? This depends on the implementation of the algorithm, such as threadlocal in the practice is to find out the position of the first empty position, the placement of data, HashMap is linked to the chain structure. Anyway, as long as the guarantee to put the time and take the algorithm consistent on the line.

4, if the ID of the hashcode%8 equal what to do (this corresponds to the 3rd said the chain structure of the scene)? It's time to define equals. The hashcode%8 is the first to determine the position of the class, and then by equals to find the desired class in this position. Compare two classes of time also similar, first through hashcode comparison, if hashcode equal again Judge equals. if the hashcode of the two classes are not the same, then the two classes must be different .

Give a practical example of set. We know that the elements inside the set cannot be duplicated, so how do we do that? Set is based on the Equals () method to determine whether two elements are equal. Let's say that there are already 1000 elements in the set, so when the 1001th element comes in, it is possible to call the Equals method up to 1000 times, and if the Equals method is more complex and contrasting, then the efficiency will be greatly reduced. Using Hashcode is not the same, for example HashSet, the bottom is based on HASHMAP implementation, first through the hashcode to take a mold, so suddenly fixed to a position, if there is no element in this position, Then you can be sure that there is no element in the hashset and the newly added elements of the equals, you can directly store, do not need to compare; if there are elements in this position, compare each other, compare the time of the first comparison hashcode,hashcode are different, certainly not the same Like, Hashcode equal, and then equals, no same element exists, there is no same element exists. If the original set has the same elements, as long as the Hashcode generation method is well defined (not duplicated), regardless of how many elements in the original set, only need to execute once equals. As a result, the number of actual calls to the Equals method is greatly reduced, increasing efficiency.

Why rewrite the Equals () method in Java to override the Hashcode () method?

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.