Java record -24-equals method overrides

Source: Internet
Author: User

Java Equals method overrides

If we ask for the same person when the ID of two students is the same, the code is implemented as follows:

Public class equalstest {    public static void main (String[ ] args)  {        Student s1 = new  Student (        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;        }       &Nbsp; if (obj instanceof student) {             Student s =  (Student) obj;             if (s.id == this.id) {                 return true;             }        }         return false;    }}

When we do not rewrite the Equals method of the object class, the above requirement cannot be implemented because the Equals method inherits from the parent class object, and implements the comparison of the reference addresses of the two objects in a consistent manner.

We only have to rewrite the Equals method of the parent object: When the comparison of two objects is the same, it can be the same; when it is not the same object, the first thing to see is whether the incoming object is a student type, if it is not a different, if it is the ID comparison, the same ID is the same person.

Java record -24-equals method overrides

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.