(As of 8/7/2020) </ span> </ p> </ td> </ tr> </ table> </ div>
</ p> </ td> </ tr> </ table>)
public class Human {
String name;
int hp;
public String toString(){
return "name:" + this.name + "/age:" + this.age;
}
}
In the above case
Equal value
Judgment of (==)
"Exactly the same existence" = "pointing to the same address value"
same.java
Human h1 = new Human("Taro")
Human h2 = h1;
Since h1 is assigned to h2, it has the same instance A "name: Taro".
The reference destination also refers to the same address at 2112.
At this time, "h1 == h2" holds.
Equivalent
equals.java
Human h1 = new Human("Ziro");
Human h2 = new Human("Ziro");
Create each instance → refer to
Instance A "name: Ziro" → 3322
Instance B "name: Ziro" → 9191
"H1! = H2" holds
However, the contents of the string are the same
Therefore, "h1.equalsa (h2)" holds.
Yeah, I understand.
But,
If you proceed with [Introduction to Java that you can understand clearly]([Introduction to Java that you can understand clearly]) and enter the chapter on API utilization in the latter half
It is stated that equals () does not work properly unless the evaluation standard of "what makes it the same" is specified, but it is a little confusing.
The following does not work correctly
Example 1) Compare two people
public class Main {
public static void main(String[] args) {
Human h1 = new Human();
h1.name = "Taro";
h1.age = 10;
Human h2 = new Human();
h2.name = "Taro";
h2.age = 10;
if ( h1.equals(h2) == true ) {
System.out.println("Same");
} else {
System.out.println("different") ;
}
}
}
The processing content of equals () inherited from Object class is as follows
"For the time being, if the values are equal, return true."
Will be in the form of
public boolean equals(Object o) {
if (this == o) {
return true;
} else {
return false;
}
}
"What to consider as the same content" is different for each class, so
Must be defined for each
In other words, specify by "overriding equals"
The condition is "If the names are the same, they are considered to be the same Human"
Then it will be as follows
public class Human {
String name;
int age;
public boolean equals(Object o ) {
if (this == o) {
return true;
} if (o instanceof Human) { //Additional overrides below ① Determine if o can be cast to Human type
Human h = (Human)o; //(2) Downcast Object type o to Human type and assign it to h
if ( this.name.equals(h.name)) {
return true;
}
}
return false;
}
}
"SAME" is displayed