On the Equals method of Java object

Source: Internet
Author: User

As one of the many questions asked: What is the difference between = = and equals in Java?

The general answer on the internet is: = = Compare the memory address, equals the value of the comparison.

In fact, this answer is very non-standard, a little more standard answer should be the JDK comes with some classes on the implementation of equals, for example

The definition of the equals of the object objects is this:

 Public Boolean equals (Object obj) {    return ( this = = obj);}

So there is no difference between = = and equals in object.

In string, however, the overridden Equals method is defined like this:

 Public Booleanequals (Object anobject) {if( This==anobject) {        return true; }    if(AnObjectinstanceofString) {String anotherstring=(String) AnObject; intn =value.length; if(n = =anotherString.value.length) {CharV1[] =value; CharV2[] =Anotherstring.value; inti = 0;  while(n--! = 0) {                if(V1[i]! =V2[i])return false; I++; }            return true; }    }    return false;}

Definition of equals of a long object:

 Public Boolean equals (Object obj) {    ifinstanceof  Long) {        return value = = ( Long). Longvalue ();    }     return false ;}

On the Equals method of Java object

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.