Java record-24-equals method Rewriting

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.