Why does my HashMap allow duplicate keys?

Hey, I use HashMapto track services and service requests on BulletinBoard. However, I must have hashcode and it is equally mistaken, because I get duplicate keys. Can anyone explain why this could be?

Keyset Content:

Services: [1, 1, 6, 6, 3]
Requests: [8, 7, 6, 5, 8, 4, 5, 6, 2]

Here is the relevant code:

private static final HashMap<Advert, Integer> services = new HashMap<>();
...

public class Advert {

private int id;
private BoardPoster poster;

public Advert(BoardPoster poster) {
    this.poster = poster;
}

public BoardPoster getPoster() {
    return poster;
}

public void spawn() {
    id = RANDOM.nextInt(ADVERT_RANGE);
}

public int getID() {
    return id;
}

@Override
public String toString() {
    return Integer.toString(id);
}

@Override
public boolean equals(Object o) {
    if (o != null && o instanceof Advert) {
        return ((Advert) o).id == id;
    }
    return false;
}

@Override
public int hashCode() {
    return 67 * 5 + this.id;
}
}
+5
source share
1 answer

The most likely reason is that the objects that you use as keys are mutable. Therefore, if you do something like:

map.put(anAdvert, 1);
anAdvert.spawn(); //modifies id, which affects hashcode and equals

The behavior of the card will be unexpected.

cf javadoc map

. , . , , , .

+18

All Articles