【问题标题】:Java Sort ArrayList inside an ArrayList [duplicate]ArrayList中的Java对ArrayList进行排序[重复]
【发布时间】:2019-03-14 11:24:09
【问题描述】:

我在对包含 ArrayLists 的 ArrayList 进行排序时遇到了一些问题

ArrayList<ArrayList<String>> multiMarkArray = new ArrayList<ArrayList<String>>();

String line;
while ((line = bufRdr.readLine()) != null) {
    ArrayList<String> singleMarkArray = new ArrayList<String>();
    for (String word : line.split(" ")) {
        singleMarkArray.add(word);
    }
    Collections.swap(singleMarkArray, 0, 1);
    multiMarkArray.add(singleMarkArray);
}

Collections.sort(multiMarkArray);
System.out.println(multiMarkArray);

我收到错误 Collections 无法应用于 (java.util.ArrayList>)

有人能指出我解决这个问题的正确方向吗?

谢谢

【问题讨论】:

    标签: java arraylist collections


    【解决方案1】:

    如果您想对multiMarkArray 中包含的所有列表进行排序,您应该这样做

    for (ArrayList<String> strings : multiMarkArray) {
           Collections.sort(strings);
    }
    

    而不是

    Collections.sort(multiMarkArray);
    

    这将对每个列表中的字符串进行排序。但multiMarkArray中的列表排序不会受到影响。

    【讨论】:

      【解决方案2】:

      您只能对包含实现 Comparable 的元素的集合进行排序。

      【讨论】:

        【解决方案3】:

        为了排序,您需要一个排序标准。 ArrayLists 没有内置的排序标准,因为没有自然的方法来比较两个 ArrayLists。

        您必须通过使用两个参数调用sort 的版本并传递Comparator&lt;ArrayList&lt;String&gt;&gt; 来提供标准。

        【讨论】:

          【解决方案4】:

          集合sort 适用于“可比”对象(extends Comparable):

          public static <T extends Comparable<? super T>> void sort(List<T> list)
          Sorts the specified list into ascending order, according to the natural ordering of its elements. 
          

          或者您可以使用自己的比较器发送带有第二个参数的排序方法:

          public static <T> void sort(List<T> list,
                      Comparator<? super T> c)
          Sorts the specified list according to the order induced by the specified comparator. 
          

          【讨论】:

            猜你喜欢
            • 2013-07-05
            • 2017-02-09
            • 2016-05-28
            • 2019-10-05
            • 2013-08-28
            • 2021-09-16
            • 1970-01-01
            • 1970-01-01
            • 2013-08-20
            相关资源
            最近更新 更多