Learning notes-JAVA-test site 10-Under what conditions do I need to rewrite the equals and hashcode () Methods ?, -Java-hashcode
I. Under what circumstances do I need to rewrite the equals and hashcode () methods?
1. Add the custom class objects to the hashset. to ensure that they do not repeat, you need to override the equals () and hashcode () methods for their classes.
If you do not override equals, different referenced objects with the same content will be added to the hashset as different objects.
Rewrite the sample code of equals:
Public boolean equals (Object obj) {// You cannot write a custom type reference here, so the set <span style = "white-space: pre "> </span> // the underlying framework does not call this overload method. <Span style = "white-space: pre"> </span> if (! (Obj instanceof Person) {<span style = "white-space: pre"> </span> return false; <span style = "white-space: pre "> </span >}< span style =" white-space: pre "> </span> Personp = (Person) obj; <span style =" white-space: pre "> </span> // used to check whether the equals method is called <span style =" white-space: pre "> </span> sop (this. name + "....... equals ....... "+ p. name); <span style = "white-space: pre "> </span> // two objects with the same name and age are considered as one <span style =" white-space: pre "> </span> return this. name. equals (p. name) & this. age = p. age ;}
Test results:
[Conclusion] The cyclic iteration result a2: 12 is printed twice, indicating that the duplicate element new Person ("a2", 12) is added to the set. The uniqueness of HashSet is not guaranteed.
At the same time, equals is not called, indicating that only rewriting the equals method does not work.
2. Isn't it enough to rewrite equals? Why rewrite hashcode () here ()?
A: When a hashset stores objects, it first determines whether the hash values of the two objects are the same. equals () is equal only when hashcode () is equal, the two objects are considered to be the same.
Sample Code for rewriting hashcode:
Public int hashCode (){ Sop (this. name + "... hashCode "); Return this. name. hashCode () + 29 * age; } |
3. What is the ArrayList mechanism?
[1] The HashSet judgment, deletion, and addition operations are based on the hashCode () and equals () Methods of the class where the operated element is located.
[2]. ArrayList performs the same operation based on the equals () method.
Reference: http://blog.csdn.net/benjaminzhang666/article/details/9468487 #