It is known that in the collection, the two elements in the collection are judged to be the same, depending on the hashcode () and Equals () two methods.
> A simple experiment
Public classTeacher {PrivateInteger ID =NULL; PublicTeacher (Integer id) {Super(); This. ID =ID; } @Override PublicString toString () {StringBuilder builder=NewStringBuilder (); Builder.append ("Teacher [id="). Append (ID). Append ("]"); returnbuilder.tostring (); } /*@Override public int hashcode () {final int prime = 31; int result = 1; result = Prime * result + ((id = = null)? 0:id.hashcode ()); return result; } @Override public boolean equals (Object obj) {if (this = = obj) return true; if (obj = = null) return false; if (getclass () = Obj.getclass ()) return false; Teacher other = (Teacher) obj; if (id = = NULL) {if (other.id! = null) return false; } else if (!id.equals (Other.id)) return false; return true; } */ }
View Code
Importjava.util.ArrayList;Importjava.util.Collection; Public classCall { Public Static voidMain (string[] args) {Collection<Teacher> C =NewHashset<teacher>(); for(inti = 0; I < 5; i++) {C.add (NewTeacher (i)); } System.out.println ("Collection" +c); Teacher T1=NewTeacher (1); System.out.println ("Teacher" +t1); System.out.println (C.contains (t1)); }}
View Code
After execution, you can see:
Collection, [Teacher [Id=0], Teacher [id=1], Teacher [id=2], Teacher [id=3], Teacher [id=4Teacher [id=] 1]false
View Code
It is clear that the collection considers that the object with ID 1 does not exist in the collection.
Because, the collection relies on hashcode () and Equals () to determine whether the elements are equal, and the Hashcode () object returns the address of the objects to calculate the hash code, the Equals () of object is the address of the comparison object. So, in the case of two objects (although the contents of the object are the same), the collection thinks they are different.
At this point, you need to override both methods (you can undo the comments of the two methods above) and then look at the execution results.
Of course, for some sets of linear comparisons of their elements, it is also ok to rewrite only equals (), such as ArrayList. (Of course, for the maintainability of the program, it is best to rewrite the hashcode () and Equals () , how do you know if someone later modifies it into another collection implementation type? )
"Java" hashcode () and Equals ()