A rule in Java that determines whether two objects are equal:
First, determine whether the hashcode of two objects is equal
If not equal, neither object is considered equal
If equal, determine whether two objects are equal with the equals operation
If not equal, neither object is considered equal
If equal, two objects are considered equal
We need a downward transformation in the Equals method, and the efficiency is very low, so we first judge the Hashcode method to improve efficiency.
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.
1, all Java classes inherit from the object class
The 2,object class has
public int hashcode () {}
public boolean equals (Object obj) {}
These two methods and other methods.
In the object class, the Equls () method and the nature of = = are the same, judging whether two references point to the same object.
The string class inherits from the object class: But the string class overrides the Equals () method,
Makes it possible for the Equals () method to compare the contents of two strings for equality;
the function of = = is to compare whether two references point to the same object;
Many classes rewrite the Equals method to create a new definition for themselves.
3, in this program: The items class inherits from the object class, and overrides the Equals () method, does not follow the parent class comparison method to compare two objects, so that the method can follow the programmer's own will to compare two objects
@Items. java//Resolve number No merge issue@Override Public inthashcode () {//if GetID and GetName are the same, then Hashcode must be the same return This. GetId () + This. GetName (). Hashcode ();} @Override Public Booleanequals (Object obj) {//TODO auto-generated Method Stub if( This==obj) { return true; } if(objinstanceofItems) {Items I=(Items) obj; if( This. GetId () ==i.getid () && This. GetName (). Equals (I.getname ())) { return true; } Else { return false; } } Else { return false; }}
Overriding the Equals () method and the Hashcode () method