0

我有一个未排序的链表。为了对其进行排序,我想我会将这些值放入带有比较器的 TreeSet 中,然后将这些值作为新的链表返回。然而,它失败了。

比较器:

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
    }

}

排序功能:

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

测试这些值时,一切似乎仍处于插入顺序。

4

2 回答 2

7

为什么不使用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());
  }
});

我们无法真正调试您的程序以及列表未排序的原因。能提供一个测试用例吗?签名是Species.getName()什么?是String吗?

于 2009-10-12T02:44:08.517 回答
1

这并不能直接回答您的问题,但您可能会发现使用它更容易Collections.sort,传入您的列表和比较器。使用TreeSet.

于 2009-10-12T02:44:41.730 回答