Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding hashCode when using HashMap, HashSet etc?

Tags:

java

hashcode

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?

like image 834
St.Antario Avatar asked Sep 25 '26 20:09

St.Antario


1 Answers

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;
}
like image 165
Eran Avatar answered Sep 28 '26 23:09

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!