Why is it necessary to override hashcode when Java objects override equals?

Source: Internet
Author: User

Reprinted: I think it is very useful, save up http://blog.sina.com.cn/s/blog_6e5e2eb701012qxv.html

Why rewrite hashcode () and equals ()

   First, both methods come from the object. view the original intent according to the API document. (1) Public Boolean
Equals
(Object OBJ). For any non-null reference values X and Y, this method returns true only when x and y reference the same object. Note: when this method is overwritten, it is usually necessary to override the hashcode method to maintain the conventional protocol of the hashcode method, which declares that the equivalent object must have an equal hash code. (2) Public int
Hashcode() Returns the hash value of the object. This method provides some advantages for hash tables, for example,java.util.HashtableProvided hash table.

   We know that if equals is not rewritten, It will compare whether the object reference points to the same memory address. After rewriting, the purpose is to compare whether the values of the two objects are equal. In particular, when equals is used to compare eight packaging objects (such as int and float) and string objects (because the equals and hashcode methods have been overwritten, by default, values are compared, and other objects are compared with reference addresses. Why is it necessary to rewrite the hashcode in JDK when we want to rewrite equals?

   In my understanding, hashcode is used for fast access to hash data. For example, when using the hashset/hashmap/hashtable class to store data, both are based on the hashcode value of the stored object to determine whether it is the same. In this way, if we override euqals for an object, that is, as long as the object's member variables are all equal, euqals is equal to true, but hashcode is not overwritten, then we will create a new object, when the original object. when equals (new object) is equal to true, the hashcode of the two is different, which leads to different understandings, such as when storing a hash set (such as set class ), two objects with the same value will be stored, resulting in confusion. Therefore, hashcode needs to be rewritten. To ensure this consistency, the following requirements must be met:Two conditions:

   (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

    The following is a simple example.

Import java. util .*;

Class beana {
Private int I;

Public beana (int I ){
  This. I = I;
}

Public String tostring (){
  Return" "+ I;
}

Public Boolean equals (Object O ){
  Beana A = (beana) O;
  Return (a. I = I )? True: false;
}

Public int hashcode (){
  Return I;
}

}

Public class hashcodetest {

Public static void main (string [] ARGs ){
  Hashset <beana> set = new hashset <beana> ();
  For (INT I = 0; I <= 3; I ++ ){
   Set. Add (New beana (I ));
  }
  System. Out. println (SET );
  Set. Add (New beana (1 ));
  System. Out. println (set. tostring ());
  System. Out. println (set. Contains (New beana (0 )));
  System. Out. println (set. Add (New beana (1 )));
  System. Out. println (set. Add (New beana (4 )));
  System. Out. println (SET );

}

}

We have rewritten the equals and hashcode methods in the beana class. In this way, duplicate data will not appear in the data set stored in the hashset. If we remove the two methods, the duplicate data will still be stored in the hashset, which is contrary to the uniqueness of the elements emphasized by the hashset. you can comment out the two methods and run them again.

Combined with others' answers to understand a lot: http://zhidao.baidu.com/question/287474398.html&__bd_tkn__=6ea745613d6c9d624f1abf638da423b9984f95e78078338d51fed8133ea5c69d362ad36bb4bcda3b39bb3949f6bbe47087ac3af56e60b1f4e7eb60157a54fa369a63aaf1560f03de0125276ad431bc063c759d727922#finish-value

Why do I need to override the hashcode METHOD FOR THE equals method of the object class in Java? Can I not rewrite it?

The requirements need to be rewritten. In practice, it can be not rewritten. the compiler will not report errors, and generally there will be no problems, as long as you do not need to store these objects like hashtable. The hashcode and equals must be consistent, but the hashtable problem is the main consideration. For example, if you override the equals method of Class A, and there are two objects A1 and A2 which are equal according to this method. Now you need to put these two objects into hashtable h as the key (similar to the name) of the other two objects V1 and V2 respectively, that is, to: H. put (A1, V1); H. put (A2, B2); in this way, because A1 and A2 are equal, put (A2, B2) should overwrite A1. In other words, if you put (A1, B1); and then, use the get method H. Get (A1) and H. Get (A2) to get B1. If you think this is not intuitive, you can think of A1 and A2 as two strings. However, if you do not override the hashcode method, the above objectives cannot be completed. Although we think A1 and A2 are equal and equals are true, the problem is that the hash table does not use equals to determine whether two objects are equal! To give a hash table a key value, he will use the hashcode method to obtain the hash code of this key value, that is, the hashcode value, and use it as the actual index to manage the entire table, if you have learned the data structure, you should know the management process. Conversely, if the author of the string class only overrides equals but does not overwrite the hashcode method, we execute the following two operations: H. Put ("AAA ",
B1); H. Put ("AAA", B2); two key-value pairs will be created in hashtable, while H. Get ("AAA") will not get B1 or B2.

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.