First, under what circumstances need to rewrite equals and Hashcode () two methods?
1. Add the object of the custom class in HashSet, to ensure that they do not repeat, need to rewrite equals () and Hashcode () methods on their class.
If you do not override equals, objects with different references to the same content will be added to the HashSet as different objects.
Rewrite The example code for equals ():
public boolean equals (Object obj) {//This can not be written as a custom type custom type reference, so set <span style= "White-space:pre" ></span> / The bottom of the/close frame does not call this overloaded 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>//is used to see if 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 that have the same name and age are one <span style= "White-space:pre" ></span>return this.name.equals (p.name) && This.age = = P.age;}
Test results:
"Conclusion" loop iteration Result: A2::12 was printed two times, indicating that the repeating element new person ("A2", 12) was added to the collection. There is no guarantee of the uniqueness of the hashset.
At the same time equals is not invoked, stating that just overriding the Equals method does not work
Two, not rewrite equals is enough, why do you want to rewrite hashcode ()?
A: HashSet when storing objects, first determine whether the hash value of two objects is the same, only if hashcode () equal Equals () is equal, only when two objects are considered the same.
Rewrite the sample code for Hashcode:
public int hashcode () { SOP (THIS.name + "... hashcode"); return This.name.hashCode () + 29*age; } |
Thirdly, what is the mechanism of ArrayList?
[1]. HashSet judgment, deletion, and addition of elements are based on the hashcode () and Equals () methods of the class in which the element is being manipulated.
[2]. ArrayList do the same, based on only the Equals () method
Reference: http://blog.csdn.net/benjaminzhang666/article/details/9468487#
Learning Note-java-Test Center 10-When do I need to rewrite equals and Hashcode () two methods?