Java Reference
In-Depth Information
sse.add(e1);
sse.add(e2);
System.out.println(sse);
System.out.println(e1.equals(e2));
}
}
class Employee implements Comparable<Employee>
{
private String name;
Employee(String name)
{
this.name = name;
}
@Override
public int compareTo(Employee e)
{
return name.compareTo(e.name);
}
@Override
public String toString()
{
return name;
}
}
Listing 5-11 ' s main() method differs from Listing 5-10 in that it also creates two
Employee objects initialized to "john doe" , adds these objects to the sorted set,
andcomparestheseobjectsforequalityvia equals() .Furthermore, Listing5-11 de-
clares Employee toimplement Comparable ,introducinga compareTo() method
into Employee .
When you run this application, it generates the following output:
[Bob Doe, John Doe, Sally Doe]
false
Thisoutputshowsthatonlyone "john doe" Employee objectisstoredinthe
sortedset.Afterall,asetcannotcontainduplicateelements.However,the false value
Search WWH ::




Custom Search