Soweit ich weiß, muss jedes equals-Objekt den gleichen Hash-Code haben. Was aber, wenn in der equals -Methode mehrere haben, wenn das befolgt werden muss?Java Hash Code-Implementierung mit mehreren gleich und wenn
Position ist ein Objekt, Junction ist ein Objekt, Länge ist eine ganze Zahl, Offset ist eine ganze Zahl, Abschnitt ist ein Objekt.
Ich löste bereits die eine, wenn atAJunction Methode, der Hashcode ich nur Junction als zusätzliche Hashcode verwendet. Wenn Section gleich ist, entspricht die Länge des Abschnitts dem Offset der beiden Positionen. Der Hashcode, den ich dafür benutzt habe, benutzt nur Sektion als Hashcode.
Das Hauptproblem ist, wenn sie unterschiedlichen Abschnitt, aber gleichen Offset und EndPoint haben. Es ist gleich, aber der Hashcode ist anders.
Kann jemand mit meinem Problem helfen? Danke vorher. :)
Das ist meine Equals-Methode:
@Override
public boolean equals(Object object) {
if(object == null){
return false;
}
if(!(object instanceof Location)){
return false;
}else{
Location otherLocation = (Location) object;
if(atAJunction() && otherLocation.atAJunction()){
return this.endPoint.getJunction().equals(otherLocation.getEndPoint().getJunction());
}else{
// The Problem Here
if(this.endPoint.equals(otherLocation.endPoint)){
return this.offset == otherLocation.getOffset();
}else{
return this.section.equals(otherLocation.getSection()) &&
this.section.getLength() == (this.offset + otherLocation.getOffset());
}
}
}
}
Und das ist mein Hash-Code:
@Override
public int hashCode() {
// creates a polynomial hash-code based on the fields of the class.
final int prime = 13; // an odd base prime
int result = 1; // the hash code under construction
if(atAJunction()){
result = prime * result + this.endPoint.getJunction().hashCode();
}else{
result = prime * result + this.section.hashCode();
}
return result;
}
Sind Sie sicher, dass die equals-Methode korrekt ist? Denken Sie daran, dass Gleichheit reflexiv sein muss: Wenn a.equals (b) und b.equals (c) dann a.equals (c) - Ich sehe nicht, wie Sie das garantieren können – Joni
Als eine Nebenbemerkung, wenn eine if-Anweisung nur enthält eine return-Anweisung, verwenden Sie kein "else" danach, weil es redundant ist und eine Menge Unordnung zum Code hinzufügt – niilzon