Java:TreeSet和LinkedList的问题

Nic*_*ner 0 java sorting linked-list comparator treeset

我有一个未分类的链表.为了对它进行排序,我想我会将值放入一个带有比较器的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
    }

}
Run Code Online (Sandbox Code Playgroud)

排序功能:

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

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

not*_*oop 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());
  }
});
Run Code Online (Sandbox Code Playgroud)

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