Generally, all classes should replicate the Equals method in object. The steps are roughly three-step:
1) Determine whether the address of two objects is consistent
2) Determine if the second object is the same subclass instance
3) Determine whether the content is consistent
classperson{ Public intAge ; PublicString name; PublicPerson (intAge , String name) { This. Age =Age ; This. Name =name; } Public Booleanequals (Object obj) {//The first step is to determine whether the two object addresses are consistent if( This==obj)return true; //determines whether the second object is the same subclass instance if(! (objinstanceofPerson )) return false; //Judging whether the content is consistentPerson Anotherone =(person) obj; if( This. Name = =NULL&& Anotherone.name! =NULL) return false; if( This. Name.equals (Anotherone.name) && This. Age = =anotherone.age)return true; return false; }} Public classhello{ Public Static voidMain (string[] args) {person P1=NewPerson ("cherry")); Person P2=NewPerson ("cherry")); System.out.println (P1.equals (p2)); } }
Replication Equals method in Java