Java equals function usage details

  • 2020-04-01 01:26:32
  • OfStack

The equals function has been defined in the base class object, the source code is as follows
 
public boolean equals(Object obj) { 
return (this == obj); 
} 

Can be seen from the source of the default equals () method with "= =" is consistent, all is the object of reference, rather than the object values (here with our common sense of the equals () is used for object comparison phase Bo, the reason is that most of the Java classes override the equals () method, the following is the String class, for example, the String class equals () method of the source code is as follows:)
[Java]
 
 
private final char value[]; 

 
private final int offset; 

 
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 () for the String class is very simple, just convert the String class to an array of characters for bit-by-bit comparison.
To sum up, using equals () method we should pay attention to:
1. To apply equals () to a custom object, you must override the system's equals () method in the custom class.
A little knowledge, much trouble.

Related articles: