Then, when comparing ==, it becomes false.
String overrides HashCode () and equals ().
The above equals
True if the object has the same address
False if the comparison string class is not String
False if the comparison string class lengths are not the same 4, compare in loop, false if wrong
True when the loop is completed
HashCode () and equals () on your own
private static class Person { int age; String name;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return name + " - " +age;
}
/**
* @desc
*/
@Override
public boolean equals(Object obj){
if(obj == null){
return false;
}
if(this == obj){
return true;
}
if(this.getClass() != obj.getClass()){
return false;
}
Person person = (Person)obj;
return name.equals(person.name) && age==person.age;
}
@Override
public int hashCode() {
return this.name.hashCode();
}
}
Sample code https://github.com/YanHengGo/java/tree/master/04_hashcode
Recommended Posts