Java record-24-equals method Rewriting
If we want to rewrite the Java equals method, when two students have the same id, the code is implemented as follows:
Public class initialize stest {public static void main (String [] args) {Student s1 = new Student (112); Student s2 = new Student (112); System. out. println (s1.equals (s2) ;}} class Student {private int id; public Student (int id) {this. id = id;} public boolean equals (Object obj) {if (this = obj) {return true;} if (obj instanceof Student) {Student s = (Student) obj; if (s. id = this. id) {return true ;}} return false ;}}
When we do not override the equals method of the Object class, the above requirements cannot be met, because the equals method inherits from the parent class Object, and the implementation is to compare whether the reference addresses of the two objects are consistent. We only need to override the equals method of the parent class Object: when the two objects to be compared are the same, they can be the same; when not the same Object, first, check whether the passed object is of the student type. If it is not customizable or different, compare the IDs. If it is the same, it is the same person.