2009-10-12 26 views
0

我有一个未排序的链接列表。为了对它进行排序,我想我会将值放入一个TreeSet中,并提供一个比较器,然后将这些值作为新的链表返回。然而,它失败了。Java:TreeSet和LinkedList的问题

比较:

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); 
} 

当测试值,一切似乎仍然是按插入顺序。

+0

请添加物种类和一些测试用例。我已经减少了物种类到字符串,一切正常。 – sanscore 2009-10-12 03:07:25

回答

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

+0

你应该链接到采用“比较器”的重载。 :-D – 2009-10-12 02:45:32

1

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

+1

另外,TreeSet可能会因消除具有重复名称的项目而产生无意的副作用。 – 2009-10-12 02:52:56