简体   繁体   English

如何排序ArrayLists列表(不是数组)?

[英]How to sort a List of ArrayLists (not arrays)?

I have an adjacency list implemented using a List[] of ArrayLists. 我有一个使用ArrayLists的List []实现的邻接表。 I want to sort the List in descending order of the size of the ArrayLists. 我想按ArrayLists大小的降序对List进行排序。 I figured I would do this by writing a Comparator... But how would I do this? 我以为我会写一个Comparator来做到这一点。。。但是我该怎么做呢? or is this just not possible and I should do it another way? 还是这是不可能的,我应该换一种方式?

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

The code on top is not functioning. 最上面的代码不起作用。 I tried with just an ArrayList, List[], List as a Comparator type. 我尝试仅使用ArrayList,List [],List作为比较器类型。 Is there a wrapper class for list? 有列表的包装器类吗? Sorry if this may sound uneducated. 抱歉,这听起来似乎没有根据。

This is how I made the adjacency list: 这是我制作邻接表的方式:

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

Thank you. 谢谢。

The code on top is not functioning. 最上面的代码不起作用。

The code is not working because p1 and p2 are ArrayLists and they dont have a field named length, they have the method size() , that is what you need. 该代码无法正常工作,因为p1和p2是ArrayLists,它们没有名为length的字段,它们具有size()方法,这就是您所需要的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM