我有一个带有一些Tree节点的List,想要对它进行排序。作为比较器,我使用List中每个节点拥有的双变量。
这是我的代码:
List<TreeNode<String>> list = inputNode.getChildren();
for(TreeNode<String> childNode : list)
{
Collections.sort(list, childNode.costs);
}
TreeNode的定义如下:
public class TreeNode<T> {
public T data;
public double costs;
public List<TreeNode<T>> children;
// Bunch of getters and setters
}
我尝试做的是对子节点列表进行排序(降序)。我不想写一些已经存在的新东西。那么为什么我不能使用Collections.sort
?
Collections.sort double
不是可比较的数据类型吗?
答案 0 :(得分:1)
你应该以稍微不同的方式使用它。
TreeNode必须实现Comparable http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html或将比较器写为匿名类。
public class TreeNode<T> implements Comparable {
public T data;
public double costs;
public List<TreeNode<T>> children;
// Bunch of getters and setters
public int compareTo(TreeNode that) { return (int)(this.cost - that.cost); }
}
或
Collections.sort(ls, new Comparator()
{
public int compare(Object o1, Object o2)
{
//typecast and compare here
}
}
);
并且,不要在循环中调用Collections.sort。一个电话就足够了。
答案 1 :(得分:0)
您有两种选择: 1)使类TreeNode实现Comparable&lt; TreeNode&lt; T&gt;&gt;并实现compareTo方法, 2)创建比较器&lt; TreeNode&lt; T&gt;&gt;并使用Collections.sort(list,comparator);
答案 2 :(得分:0)
我可能错了,但TreeNode<T>
本身不应该实施可比较的?然后你可以比较节点上的值吗?