【问题标题】:How to sort a List of ArrayLists (not arrays)?如何对 ArrayLists 列表(不是数组)进行排序?
【发布时间】:2017-08-08 07:06:34
【问题描述】:

我有一个使用 ArrayLists 的 List[] 实现的邻接列表。我想按 ArrayLists 大小的降序对列表进行排序。我想我会通过写一个比较器来做到这一点......但我该怎么做呢?或者这是不可能的,我应该用另一种方式来做?

Collections.sort(adjacency, new Comparator<ArrayList<Integer>()>() {
    public int compare(ArrayList<Integer> p1, ArrayList<Integer> p2) {
        return Integer.compare(p1.length, p2.length);
    }
});

上面的代码不起作用。我尝试使用 ArrayList、List[]、List 作为比较器类型。是否有列表的包装类?对不起,如果这听起来没有受过教育。

这就是我制作邻接列表的方式:

List<Integer>[] adjacency;
adjacency = (List<Integer>[]) new List[size];
for (int i = 0; i < size; ++i) {
    adjacency[i] = new ArrayList<Integer>();
}

谢谢。

【问题讨论】:

  • 不应该 p1.lengthp1.size() 吗?所以你有一个ArrayLists 的数组,你正在尝试使用Collections.sort 对数组进行排序...?

标签: java list sorting arraylist comparator


【解决方案1】:

上面的代码不起作用。

代码不起作用,因为 p1 和 p2 是 ArrayList,它们没有名为 length 的字段,它们有方法 size(),这正是您所需要的。

return Integer.compare(p1.size(), p2.size());

【讨论】:

  • 在你回答这个问题之前我会非常小心,并仔细看看他们是如何创建adjacency ;)
猜你喜欢
  • 2011-12-09
  • 1970-01-01
  • 2015-01-03
  • 2018-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多