Detailed explanation of equals method

/*
About the equals method in Object:
public boolean equals (Object obj){
return (this==obj);
}
o1.equals(o2), o1 is this, o2 is obj
== If both sides are reference types, compare The design purpose of the equals method in the memory address java object: to determine whether two objects are the same */ public class fuck2{ public static void main(String[] args){ Object o1=new Object(); Object o2=new Object() ; boolean b1=o1.equals(o2); System.out.println(b1);//false star s1=new star(100,"haha"); star s2=new star(100,"haha"); star s3=new star(110,"haha"); System.out.println(s1.equals(s2));//true System.out.println(s2.equals(s3));//false } class star {



























int id;
String name; public star(int id,String name){ this.id=id; this.name=name; } //The equals method in Object compares the memory address /*In real business logic, it is not The memory address should be compared, and the content should be compared. Therefore , the equals method in Object should also be rewritten. The equals method should be rewritten according to the requirements. The requirements stipulate: if the ID number is the same and the name is the same, it means the same person */   public boolean equals(Object obj){ if (this==obj) return true; if(obj instanceof star){ //Force type conversion star s=(star)obj; if(s.id==id&&s.name.equals(name)){ return true; } } return false; } }


























Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325891306&siteId=291194637