Functions of the Java-equals function (44th sets)

Source: Internet
Author: User

The following is a java4android video tutorial from marschen.

Main content of this set.
1. Where is the equals function.
2. Functions of the equals function.
3. Method for rewriting the equals function.

A. Equals is included in the object. The object is the parent class of all classes.
Therefore, all classes inherit the equals method.
B. Check whether the two references point to the same address in the heap memory. or
Is the same object.

Code on
 
The equals function is used to compare whether the content of two objects is equal.
Normally, whether the content of two objects is equal. The two conditions must be met.
A. The object type is the same (you can use the instanceof operator for comparison ).
B. The values of the member variables of the two objects are identical.

class User{ String name; int    age;  public boolean equals(Object obj){ if(this == obj){ return true; }  boolean b = obj instanceof User; if(b){ User u = (User)obj; if(this.age == u.age && this.name.equals(u.name)){ return true; } else{ return false; } } else{ return false; } }}
class Test{public static void main(String args[]){User u1 = new User();User u2 = new User();User u3 = new User();u1.name = "zhangsan";u1.age  = 12;u2.name = "lisi";u2.age  = 12;u3.name = "zhangsan";u3.age  = 12;System.out.println(u1.equals(u2));System.out.println(u1.equals(u3));//User u3 = u1;//boolean b1 = u1 == u2;//boolean b2 = u1 == u3;//System.out.println(b1);//System.out.println(b2);//boolean b1 = u1.equals(u2);//System.out.println(b1);}}

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.