Java equals function usage

Source: Internet
Author: User

The equals function has been defined in the base class object. The source code is as follows: Copy codeThe Code is as follows: public boolean equals (Object obj ){
Return (this = obj );
}

From the source code, we can see that the default equals () method is the same as "=", and both are reference of comparative objects, rather than object values (equals () in common sense () the comparison for objects is relative because most classes in java have rewritten the equals () method. The following is an example of the String class. The source code of the String equals () method is as follows :)
[Java]Copy codeThe Code is as follows:/** The value is used for character storage .*/
Private final char value [];

/** The offset is the first index of the storage that is used .*/
Private final int offset;

/** The count is the number of characters in the String .*/
Private final int count;

[Java] view plaincopyprint?
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;
}
} // Www. software8.co
Return false;
}

The equals () of the String class is very simple. It only converts the String class to a character array for comparison by bit.
In summary, we should note the following when using the equals () method:
1. If equals () applies a custom object, you must overwrite the system's equals () method in the Custom class.
2. Little knowledge, great trouble.

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.