HashCode
Hash code is to override the behavior of HashSet. By default without this, it will take the references of that class - which is a hit or miss.
Note: for this to work you need to @Override
both equals()
and hashCode()
Example
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
Person a = Person.fromName("Peter");
Person b = Person.fromName("Peter");
Set<Person> test = new HashSet<>();
test.add(a);
test.add(b);
test.forEach(item -> System.out.println(item));
}
}
class Person {
private String name;
public static Person fromName(String name) {
return new Person(name);
}
private Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return name;
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public boolean equals(Object o) {
// NOTE: need this, without this it won't work
if (this.getClass() != o.getClass()) return false;
Person oPerson = (Person) o;
return oPerson.getName() == this.getName();
}
}