Java hashcode (), Equals ()

Source: Internet
Author: User

Transferred from: http://blog.csdn.net/fenglibing/article/details/8905007 Feng Libin's Blog

The following is an official document definition for hashcode:

  1. The Hashcode method returns the hash code value of the object. This method is supported to provide some advantages to the hash table, for example, the Hashtable provided by Java.util.Hashtable.
  2. The general agreement of Hashcode is:
  3. During Java application execution, when the Hashcode method is called multiple times on the same object, the same integer must be returned consistently, provided that the information used in the Equals comparison on the object has not been modified. The integer does not need to be consistent from one execution of an application to another execution of the same application.
  4. If two objects are equal according to the Equals (object) method, calling the Hashcode method on each object in two objects must produce the same integer result.
  5. The following conditions are not required: If two objects are not equal according to the Equals (Java.lang.Object) method, then calling the Hashcode method on any of the two objects must produce a different integer result. However, programmers should know that generating different integer results for unequal objects can improve the performance of the hash table.
  6. In fact, the Hashcode method defined by the object class does return different integers for different objects. (This is typically done by converting the object's internal address to an integer, but the JAVATM programming language does not require this implementation technique.) )
  7. When the Equals 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.


The above-mentioned official document definition, we can be drawn into the following key points:

1, the existence of hashcode is mainly used to find the fast, such as Hashtable,hashmap, Hashcode is used in the hash storage structure to determine the storage address of the object;

2, if two objects are the same, is applicable to the Equals (Java.lang.Object) method, then the two objects must be the same hashcode;

3, if the object's Equals method is overridden, then the object's hashcode also try to rewrite, and produce hashcode used objects, must be consistent with the use of the Equals method, otherwise it will violate the above mentioned 2nd;

4, two objects of the same hashcode, does not necessarily mean that two objects are the same, that is not necessarily applicable to the Equals (Java.lang.Object) method, only can explain that the two objects in the hash storage structure, such as Hashtable, they " stored in the same basket. "

Again, the hashcode is used for lookup purposes, and equals is used to compare the equality of two objects. The following is a copy of the message from someone else's post:

1.hashcode is used to find, if you have learned the data structure you should know that in the Find and sort this chapter has
    1. For example, there is such a location in memory   
    2. 0  1  2  3  4   5  6  7    
    3. and I have a class, this class has a field called ID, I want to store this class in one of the above 8 locations, If you do not use hashcode and arbitrary storage, then when looking for the need to go to these eight locations to look for, or use a two-way algorithm.   
    4. but if you use hashcode it will make a lot more efficient.   
    5. We have a field called ID in this class, so we define our hashcode as id%8, and then we store our class in the position of the remainder. For example, our ID is 9, 9 except 8 of the remainder is 1, then we put the class exists 1 this position, if the ID is 13, the remainder is 5, then we put the class at 5 this position. In this way, the remainder can be found directly by ID except  8 when the class is looked up.   
    6.   
    7. 2. But if two classes have the same hashcode what to do (we assume that the ID of the class above is not unique), For example 9 divided by 8 and 17 divided by 8 the remainder is 1, then this is not legal, the answer is: can do so. So how do you judge it? At this point, you need to define  equals.   
    8. that is to say, we first determine whether two classes are stored in a bucket by  hashcode, but there may be many classes in the bucket, then we need to go through  equals   To find the class we want in this bucket.   
    9. so. overriding Equals (), why rewrite Hashcode ()?   
    10. Think you're going to find something in a bucket, you have to get to the bucket, you don't have to rewrite hashcode () to find the bucket, the Light rewrite equals () What's the use   



Finally, let's look at a concrete example,

  1. Public class Hashtest {
  2. private int i;
  3. public int Geti () {
  4. return i;
  5. }
  6. public void SetI (int i) {
  7. this.i = i;
  8. }
  9. public int hashcode () {
  10. return i% 10;
  11. }
  12. public final static void Main (string[] args) {
  13. Hashtest a = new Hashtest ();
  14. Hashtest B = new Hashtest ();
  15. A.seti (1);
  16. B.seti (1);
  17. setnew hashset
  18. Set.add (a);
  19. Set.add (b);
  20. System.out.println (a.hashcode () = = B.hashcode ());
  21. System.out.println (A.equals (b));
  22. SYSTEM.OUT.PRINTLN (set);
  23. }
  24. }


The result of this output:

    1. True
    2. False
    3. [[Email protected], [email protected]]


The above example, we just rewrite the Hashcode method, from the above results can be seen, although the two objects hashcode equal, but actually two objects are not equal, we did not rewrite the Equals method, then the object is called the default Equals method, Is the comparison of two objects is not the same, showing that this is two different objects, two object references must be indeterminate. Here we put the generated object into the HashSet, and HashSet only can hold a unique object, that is, the same (for the Equals method) of the object will only hold one, but here is actually two objects, a, a, a, is put in the HashSet, So the HashSet lost his own meaning.

At this point we add the Equals method:

public class Hashtest {
  1. private int i;
  2. public int Geti () {
  3. return i;
  4. }
  5. public void SetI (int i) {
  6. this.i = i;
  7. }
  8. <span style="color: #3366FF;" ><strong>public Boolean equals (Object object) {
  9. if (object = = null) {
  10. return false;
  11. }
  12. if (object = = this ) {
  13. return true;
  14. }
  15. if (! ( Object instanceof Hashtest)) {
  16. return false;
  17. }
  18. Hashtest other = (Hashtest) object;
  19. if (other.geti () = = This.geti ()) {
  20. return true;
  21. }
  22. return false;
  23. }</strong></span>
  24. public int hashcode () {
  25. return i% 10;
  26. }
  27. public final static void Main (string[] args) {
  28. Hashtest a = new Hashtest ();
  29. Hashtest B = new Hashtest ();
  30. A.seti (1);
  31. B.seti (1);
  32. setnew hashset
  33. Set.add (a);
  34. Set.add (b);
  35. System.out.println (a.hashcode () = = B.hashcode ());
  36. System.out.println (A.equals (b));
  37. SYSTEM.OUT.PRINTLN (set);
  38. }
  39. }

The result will be as follows:

True
    1. True
    2. [[email protected]]


As we can see from the results, two objects are now completely equal, and only one copy of the object is stored in the hashset.

The relationship between Hashcode and equals:

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).
Conversely: hashcode () can not be equal to the introduction of equals (), and hashcode () is equivalent, Equals () may be equal or unequal. To explain the scope of use of the 3rd, my understanding is that it can be used in classes such as Object, string, and so on. In the object class, the Hashcode () method is the local method that returns the address value of the object, and the Equals () method in the object class compares the address values of the two objects, and if Equals () is equal, the two object address values are equal, of course hashcode ( In the String class, Equals () returns a comparison of two object contents, and when two object contents are equal,
The Hashcode () method is based on the parsing of the string class (which is already parsed in the 2nd), and it is also known that hashcode () will return the same result. And so on, you can know that the overridden equals () and Hashcode () methods in a wrapper class such as Integer and double are also appropriate for this principle. Of course, there are no overridden classes that follow this principle after inheriting the Equals () and Hashcode () methods of the object class.

Specific uses of hashcode and equals:

When it comes to hashcode () and Equals (), we can not but mention the use of hashset,hashmap,hashtable, what is the specific, see the following analysis:
HashSet is an inherited set interface, and the set interface implements the collection interface, which is a hierarchical relationship. So what is the principle of hashset to access objects?
Duplicate objects are not allowed in hashset, and the position of the elements is indeterminate. In the HashSet, how to determine whether the elements are duplicated? This is the crux of the problem, after an afternoon of query verification finally got a little revelation, and share with you, in the Java collection, the rule to determine whether two objects are equal:
1) to determine whether the hashcode of two objects are equal
If it is not equal, the two objects are not equal, complete
If equal, transfer to 2)
(This is only to improve the storage efficiency requirements, in fact, it is not possible, but if not, the actual use of efficiency will be greatly reduced, so we will do it as necessary.) The question will be highlighted later. )
2), determine whether two objects are equal by equals
If not equal, neither object is considered equal
If equal, two objects are considered equal (equals () is the key to determine whether two objects are equal)
Why is the two rule not to use the first one? No, because as already said, the Equals () method may also be unequal when hashcode () is equal, so it is necessary to use the 2nd rule to limit the inclusion of non-repeating elements.

About the problem of re-equals () and Hashcode () in Hibernate's Pojo class:
1), the focus is equals, rewrite hashcode just technical requirements (in order to improve efficiency)
2), why do you rewrite equals, because in the Java collection frame, you are using equals to determine whether two objects are equal
3), in Hibernate, the set collection is often used to hold related objects, and set collections are not allowed to be duplicated. Let's talk about the criteria for how to tell if an object is the same when adding elements to the HashSet collection, which says two, as long as you rewrite the Equals () clause.
However, when the elements in the hashset are relatively long, or the overridden Equals () method is more complex, we only use the Equals () method to compare the judgement, the efficiency is very low, so introduced the hashcode () This method, just to improve efficiency, But I think this is very necessary (so we hashset the elements in the previous two rules to determine whether the element is repeated).
For example, it can be written like this:
public int hashcode () {
return 1;} Equivalent to hashcode invalid
The effect of this is to compare the hash code can not be judged, because each object returns a hash code is 1, each time must be compared to the Equals () method to determine whether or not to repeat, which of course will cause a significant reduction in efficiency.
I have a question, if it is the Equals () method (according to the view found on the Internet) that is necessary to judge whether an element is duplicated in HashSet, as mentioned earlier, but there is no question about a hash table, but this set is called HashSet, why??
I think the storage operation in Hashmap,hashtable still adheres to the above guidelines.

Personal Summary:

Determine whether two classes are equal, using equals. Then first use the Hashcode method, to determine whether its hashcode is equal, if not, then two classes must be unequal, if equal, then two classes may be equal, may also be unequal, this time you need to call equals to judge. The advantage of this is that it improves efficiency. Therefore, in the hashcode and Equals method, the content of the judgment cannot be the same, otherwise it loses the meaning.

Hashcode is an identity that goes to the hash table to find an identity for the object, and if the same hashcode class is placed in the same hash table, then the corresponding object in the hash list is further selected by equals. Therefore, the class under the same identity cannot be duplicated, which is also the basis for storing data such as Hashmap,hashset.

Java hashcode (), Equals ()

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.