Equals method
The Equals method, which is used to compare two objects, is actually compared with the memory address of two objects. the equals method inside the object class is used internally by the = = comparison operator (comparing memory addresses).
In development, to compare two objects is the same, often based on the value of the property in the object comparison, that is, in development often requires subclasses to override the Equals method to compare the property values of the object. The following code shows:
/*
Describe people in this class, and define the function according to age to determine whether it is peer
Because you want to compare the properties of a specified class, just overwrite the Equals method in Object
To compare the property values of a class in a method body
*/
Class Person extends object{
int age;
The Equals method of the replication parent class to achieve its own comparison
public boolean equals (Object obj) {
Determines whether the object that is currently calling the Equals method is the same as the object passed in
if (this = = obj) {
return true;
}
Determines whether the passed in object is a person type
if (! ( obj instanceof person) {
return false;
}
Transform obj down to a perosn reference, accessing its properties
Person P = (person) obj;
return this.age = = P.age;
}
}
Note : when copying the Equals method in an object, be sure to note that the public boolean equals (object obj) argument is of type object, and the type conversion is necessary when invoking the properties of the object. Type judgments must be made before the conversion.
ToString Method
The ToString method returns the string representation of the object, in fact the string content is the type of the object [email protected]+ memory address value.
Because the ToString method returns the memory address, in development, it is often necessary to get the corresponding string representation of the object's properties, so it needs to be rewritten as well.
Class Person extends object{
int age;
Override the ToString method based on the property of the person class
Public String toString () {
return "person [age=" + Age + "]";
}
}
Java, Equals method and ToString Method