The question is in the title. I use HashMap as follows:
Map<Player, Partner> m = new HashMap<Player, Partner>();
//do some on m
Where both Player and Partner are just a POJO representing data-model.
public class Player{
private int id;
private String name;
//etc, GET, SET
}
public class Partner{
private int id;
private String name;
//etc, GET, SET
}
I would like to say that two objects of those classes are equivalent iff they have the same id. So, should I write hashCode something like
public int hashCode(){
return id;
}
Is that a correct way to do that and why should I use it ever when I'm going to use HashMap or something similar?
Such hashCode would work. You'll also have to override equals in a consistent manner:
@Override
public boolean equals(Object other)
{
if (!(other instanceof Player))
return false;
Player op = (Player) other;
return id == op.id;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With