2009-10-12 29 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