Hallo,
ich habe ein Frage allgemein zu Hashverfahren, welche wir heute in Java behandelt haben.
Wir haben als Beispiel eine Klasse namens Auto entworfen für eine Hash-Tabelle.
Diese sieht so aus (Eclipse hat die Überschreibung von equals und HashCode erstellt):
public class Auto {
private int Baujahr;
private double Leistung;
private String Hersteller;
public Auto(int Baujahr, double Leistung, String Hersteller) {
super();
this.Baujahr = Baujahr;
this.Leistung = Leistung;
this.Hersteller = Hersteller;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Baujahr;
long temp;
temp = Double.doubleToLongBits(Leistung);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result
- ((Hersteller == null) ? 0 : Hersteller.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Auto other = (Auto) obj;
if (Baujahr != other.Baujahr)
return false;
if (Double.doubleToLongBits(Leistung) != Double
.doubleToLongBits(other.Leistung))
return false;
if (Hersteller == null) {
if (other.Hersteller != null)
return false;
} else if (!Hersteller.equals(other.Hersteller))
return false;
return true;
}
}
Meine Fragen:
-
ist die mathematische Berechnung des Indexes in hashCode() immer gleich oder ist das frei nach Schnauze?
-
Warum muss ich unbedingt die equals-Methode überschreiben für eine Hashtabelle?