我有一個未排序的鏈接列表。爲了對它進行排序,我想我會將值放入一個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);
}
當測試值,一切似乎仍然是按插入順序。
請添加物種類和一些測試用例。我已經減少了物種類到字符串,一切正常。 – sanscore 2009-10-12 03:07:25