Java equals function usage detailed _java

Source: Internet
Author: User
The Equals function is defined in the base class object and the source code is as follows
Copy Code code as follows:

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

From the source can see the default equals () method and "= =" is consistent, are references to the objects of comparison, not to object values (here is the comparison with our common sense equals () for objects, because most classes in Java rewrite the Equals () method, and the 饽. The following is a string class example, the string equals () method source code is as follows:
[Java]
Copy Code code as follows:

/** The value is used for character storage. */
Private final char value[];

/** the ' offset is ' the ' storage ' 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, except that the string class is converted to a character array, bitwise compared.
In summary, using the Equals () method we should note:
1. How Equals () applies the custom object, you must override the system's Equals () method in the custom class.
2. Small knowledge, big 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.