Tuesday, January 15, 2008

TreeSet Comparator

When using TreeSet(Comparator) for a sorted set, be cautious that the compare() or compareTo() must be consistent with equals. Set interface is defined in terms of the equals operation, but a TreeSet instance performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the set, equal.

E.g., unique id used in equals(), but name (could be duplicate) is used in compare() and cause problem. The item with same name actually couldn't be added to the set.


/** To sort by 2 attributes **/
public int compare(TreeElement e1, TreeElement e2) {
    // sort by tree name first
     int compareName =e1.getTreeName().compareTo(e2.getTreeName());
     if (compareName != 0) {
         return compareName;
     }
     // sort by databaseKey if tree names are the same
     return e1.getDatabaseKey().compareTo(e2.getDatabaseKey());
}

No comments: