Using a HashSet
to make sure that the computers are unique (just like you're currently doing it) is fine - assuming that you have implemented hashCode
and equals
appropriately.
In order to sort the List
of computers by name, you can just write
Collections.sort(computers, new Comparator<Computer>()
{
@Override
public int compare(Computer c0, Computer c1)
{
return c0.getName().compareTo(c1.getName());
}
});
While it might be tempting to solve this with a TreeSet
(because it can sort and remove duplicates in one run), you should carefully think about whether your comparison criterion is consistent with equals as described in the JavaDoc of TreeSet
and Comparator
:
The ordering imposed by a comparator c on a set of elements S is said to be consistent with equals if and only if c.compare(e1, e2)==0 has the same boolean value as e1.equals(e2) for every e1 and e2 in S.
( http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html )
The crucial question here is: Can there be two computers that have the same name (as returned by getName()
) but should still not be considered as "equal"?
However, if the sorting criterion is consistent with equals, then using TreeSet
with the appropriate comparator is feasible.