Java Reference
In-Depth Information
private String name;
Employee(String name)
{
this.name = name;
}
@Override
public int compareTo(Employee e)
{
return name.compareTo(e.name);
}
@Override
public boolean equals(Object o)
{
if (!(o instanceof Employee))
return false;
Employee e = (Employee) o;
return e.name.equals(name);
}
@Override
public String toString()
{
return name;
}
}
Listing5-12 correctsthe SortedSet contractviolationbyoverriding equals() .
Runtheresultingapplicationandyouwillobserve [Bob Doe, John Doe, Sally
Doe] asthefirstlineofoutputand true asthesecondline:thesortedset'snaturalor-
dering is now consistent with equals() .
Note Although it is important to override hashCode() whenever you override
equals() , I did not override hashCode() (although I overrode equals() ) in
Listing 5-12 ' s Employee class to emphasize that tree-based sorted sets ignore
hashCode() .
Search WWH ::




Custom Search