Return Value:
If the object is the same as the OBJ parametertrue
Otherwisefalse
.
Example program:
/**
* Background: your wife saw a puppy in a pet shop and asked how much it was. The boss said that the money was 5 thousand and his wife didn't get enough money.
*, Then go home to get the money, get the money, and then look at it. The puppy is sold .. The boss said that the puppy was the same color, breed, and weight as before.
* At that time, you also bought it. How do you make her feel the same as the previous puppy to make her happy?
*/
Public class test {public static void main (string [] ARGs) {dog d1 = new dog ("Puppy 1", "White", "bixiong", 3 ); dog D2 = new dog ("Puppy 2", "White", "bixiong", 3); system. out. println (d1 = d2); // falsesystem. out. println (d1.equals (D2); //} class dog {string name; string color; string category; int weight; public dog (string name, string color, string category, int weight) {This. name = Name; this. color = color; this. category = category; this. weight = weight ;}}
Output: false
At this time, you can see that my wife is trying to change a puppy .. So you have to find a solution,
// Add the following method to make the above true
Public Boolean equals (Object OBJ) {// This equals is your redefined return true; // even if it is a mouse above, your wife laughed }}
This statement is very casual. It is impossible for you to fool your wife like this. A strict definition is as follows:
// Add the following method to determine whether the two dogs are truepublic Boolean equals (Object OBJ) {// This equals is your redefined if (OBJ = NULL) return false; // if the value is null, return falseelse {If (OBJ instanceof dog) {// instanceof operator DOG d = (DOG) OBJ; // forcibly convert to the dog object if (D. name = This. name & D. color = This. color & D. category = This. CATEGORY & D. weight = This. weight) {return true ;}}return false ;}
Output:
False
True
Source code download
Knowledge Point supplement:
Equals custom Method
Object class:
"Public Boolean equals (Object OBJ)Method
Provides a logical port that defines whether an object is "equal ".
"Object equalsThe method is defined:X. Equals (y) when X and YYesSameObject Application
ReturnsTrueOtherwise, false is returned.
J2sdk provides some classes, suchString. DateOverwrite the equals method of the object and call
The equals method of these classes, X. Equals (Y), when the objects referenced by X and Y are the same Class Object and
If the property content is equal (not necessarily the same object), true is returned; otherwise false is returned.
You can rewrite the equals method in the User-Defined type as needed.