Java object equals Method

Source: Internet
Author: User

Not all equals compare the entire object.


#1. Common Object class:

First look at the source code:

   public boolean equals(Object obj) {return (this == obj);    }

If no, use "=" to compare the object reference, that is, the address. If the two objects have the same parameters but are created using new, the address is different, and false is returned using equals.


#2. String class:

First look at the source code:

    public boolean equals(Object anObject) {if (this == anObject) {    return true;}if (anObject instanceof String) {    String anotherString = (String)anObject;    int n = count;    if (n == anotherString.count) {char v1[] = value;char v2[] = anotherString.value;int i = offset;int j = anotherString.offset;while (n-- != 0) {    if (v1[i++] != v2[j++])return false;}return true;    }}return false;    }

Therefore, if the content is the same, use new to create two String objects and call equals to return true.


#3. Integer class

First look at the source code:

    public boolean equals(Object obj) {if (obj instanceof Integer) {    return value == ((Integer)obj).intValue();}return false;    }

The same is the comparison content.

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.