【问题标题】:Java: Trouble with TreeSet and LinkedListJava:TreeSet 和 LinkedList 的问题
【发布时间】:2009-10-12 02:40:30
【问题描述】:

我有一个未排序的链表。为了对其进行排序,我想我会将这些值放入提供了比较器的 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);
}

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

【问题讨论】:

  • 请添加物种类和一些测试用例。我已将物种类简化为字符串,一切正常。

标签: java sorting linked-list comparator treeset


【解决方案1】:

你为什么不用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吗?

【讨论】:

  • 您应该链接到采用Comparator 的重载。 :-D
【解决方案2】:

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

【讨论】:

  • 另外,TreeSet 可能会无意中产生消除重复名称项目的副作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-05
  • 2019-04-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多