views:

432

answers:

2

I have an unsorted linked list. To sort it, I thought I'd put the values into a TreeSet with a comparator supplied, then return those values as a new linked list. Yet, it fails.

Comparator:

public class SortSpeciesByCommonName implements Comparator<Species> {

    /**
     * a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. 
     */
    @Override
    public int compare(Species arg0, Species arg1) {
     return arg0.getName().compareTo(arg1.getName()); //arg.getName() is String
    }

}

Sorting function:

public static LinkedList<Species> sortedAnimals(LinkedList<Species> animals) {
 TreeSet<Species> sortedBreeds = new TreeSet<Species>(new SortSpeciesByCommonName());
 sortedBreeds.addAll(animals);
 return new LinkedList<Species>(sortedBreeds);
}

When testing the values, everything appears to still be in insertion order.

+5  A: 

Why don't you use Collections.sort(List,Comparator):

LinkedList<Species> sorted = new LinkedList<Species>(arg);
Collections.sort(sorted, new Comparator<Species>() {
  @Override
  public int compare(Species s1, Species s2) {
      return s1.getName().compareTo(s2.getName());
  }
});

We cannot really debug your program and why the list isn't sorted. Can you provide a test case? What's the signature of Species.getName()? Is it a String?

notnoop
You should link to the overload that takes a `Comparator`. :-D
Chris Jester-Young
+1  A: 

This doesn't answer your question directly, but you may find it easier to just use Collections.sort, passing in your list and comparator. Saves using a TreeSet.

Chris Jester-Young
Plus, the TreeSet could have the inadvertent side effect of eliminating items with duplicate names.
Jeremy Huiskamp