Jestem całkiem nowy dla java i staram się po prostu zrozumieć, jak interpretować @Override
metod equals()
i hashcode()
.
wiem na metodzie równa się być poprawne musi być:Która część umowy ogólnej equals() nie spełnia moich oczekiwań
- refleksyjne:
a.equals(a)
- symetryczny:
a.equals(b)
następnieb.equals(a)
- przechodnie:
a.equals(b) && b.equals(c)
Następniea.equals(c)
- NOT NULL:
! a.equals(null)
walczę, aby wskazać, które z powyższych właściwości jestem i jestem niespełniających pisząc mój overide metody równymi.
Jestem świadomy, że zaćmienie może je wygenerować dla mnie, jednak ponieważ nie mam jeszcze pełnego pojęcia, pisanie go pomaga mi się uczyć.
Napisałem, co uważam za poprawny sposób, ale kiedy sprawdzam z wersją generowaną przez eclipse, wydaje mi się, że "brakuje" pewnych aspektów.
Przykład:
public class People {
private Name first; //Invariants --> !Null, !=last
private Name last; // !Null, !=first
private int age; // !Null, ! <=0
...
}
Co napisałem:
public boolean equals(Object obj){
if (obj == null){
return false;
}
if (!(obj instanceof People)){
return false;
}
People other = (People) obj;
if (this.age != other.age){
return false;
}
if (! this.first.equals(other.first)){
return false;
}
if (! this.last.equals(other.last)){
return false;
}
return true;
}
vs zaćmienie generowane
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
People other = (People) obj;
if (first == null) {
if (other.first != null)
return false;
} else if (!first.equals(other.first))
return false;
if (age != other.age)
return false;
if (last == null) {
if (other.last != null)
return false;
} else if (!last.equals(other.last))
return false;
return true;
}
mi brakuje:
if (this == obj) return true;
if (getClass() != obj.getClass()) return false;
I dla każdej zmiennej:
if (first == null) { if (other.first != null) return false; } else if (!first.equals(other.first)) return false;
Nie jestem pewien, co getClass()
jest i moja implmentation błędna?
Dlaczego używasz nazwy "Name" w implementacji równań dla "People"? Wygląda jak literówka. Proszę o wyjaśnienie. – Radiodef
Możesz także zobaczyć [* "Jakiś powód, aby preferować getClass() nad instanceof podczas generowania .equals()?" *] (Http://stackoverflow.com/q/596462/2891664) Cała odpowiedź może być napisana właśnie na tylko ten temat. – Radiodef
Nadal masz, jeśli (!(obj instanceof Name)) {line wrong –