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;
}
}
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
hashCode()
.