Suppose I have this main:
import java.util.*;
public class Main {
public static void main(String[] args) {
HashSet<Persona> conjuntoPersonas= new HashSet<>();
Persona p1 = new Persona("Jose", "1");
Persona p2 = new Persona("Ivan", "2");
Persona p3 = new Persona("Alex", "2");
System.out.println(conjuntoPersonas.add(p1));
System.out.println(conjuntoPersonas.add(p2));
System.out.println(conjuntoPersonas.add(p3));
System.out.println(conjuntoPersonas.size());
}
}
And this class Person:
public class Persona {
private String nombre;
private String dni;
public Persona(String nombre, String dni) {
this.nombre = nombre;
this.dni = dni;
}
@Override
public boolean equals(Object o) {
Persona persona = (Persona) o;
return this.dni.equals(persona.getDni());
}
public String getDni() {
return dni;
}
}
I understood that when I run it I should print:
true // lo añade al conjunto
true // lo añade al conjunto
false // no lo añade al conjunto por que entiende que esta repetido
2 // imprime dos por que el tercer elemento no lo añade
However, I get
true
true
true
3
And in the debugger I see that if I add it even if it is repeated. Can someone help me understand why I do not get the desired behavior ???