Hej, używam HashMap
do śledzenia usług i zgłoszeń serwisowych na tablicy BulletinBoard. Jednak muszę mieć hashcode i jest równa, ponieważ otrzymuję zduplikowane klucze. Czy ktoś może powiedzieć, dlaczego tak się dzieje?Dlaczego moja HashMap pozwala na duplikowanie kluczy?
Zawartość Keyset:
Services: [1, 1, 6, 6, 3]
Requests: [8, 7, 6, 5, 8, 4, 5, 6, 2]
Oto odpowiedni kod:
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;
}
}
Jedna uwaga: sprawdzenie 'o! = Null && o instanceof Advert' jest zbędne. 'o instanceof Advert' zwraca' false', jeśli 'o' ma wartość' null'. W Javie 'null' nie jest uważany za typ cokolwiek, więc wszystkie instancje sprawdzają je. – Brian
Ponieważ 'id' jest' int', możesz uprościć swój hashcode: 'return this.id;'. – assylias
@assylias Jest to zły sposób na wykonanie kodu skrótu, ponieważ w rzeczywistości nie jest to haszowanie. zwracanie 'this.id% 1000' może być lepszym rozwiązaniem. –