The equals function has been defined in the base class object. The source code is as follows
Copy the code code as follows:
public boolean equals(Object obj) {
return (this == obj);
}
It can be seen from the source code that the default equals() method is consistent with "==". They are references to the objects being compared, not object values (this is consistent with our common sense that equals() is used to compare objects. The reason is that most classes in Java have overridden the equals() method. The following is an example of the String class. The source code of the equals() method of the String class is as follows:)
[java]
Copy the code code 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;
}
Equals() of the String class is very simple, it just converts the String class into a character array and compares it bit by bit.
In summary, when using the equals() method we should pay attention to:
1. Since equals() is applied to a custom object, you must override the system's equals() method in the custom class.
2. A little knowledge, big trouble.