按字母顺序对 ArrayList<String[]> 进行排序

我对 java 比较陌生,想知道如何按字母顺序对 String[] 类型的 ArrayList 进行排序。在这种情况下,我的 ArrayList 名称是 temp。基本上,String[] 将包含 3 个元素:String a、String b 和 String c。我想根据字符串 a 对数组列表进行排序。我使用 Java 10。


我试过这个,但它不起作用


ArrayList<String[]> temp = somefunction();

Collections.sort(temp);

这是显示的错误:


sort(java.util.List<T>) in Collections cannot be applied 

      to(java.util.ArrayList<java.lang.String[]>)


潇湘沐
浏览 312回答 2
2回答

人到中年有点甜

该方法Collections.sort的参数化T意味着<T extends Comparable<? super T>>应该满足条件。String[]不符合要求,因为它没有扩展Comparable。Collections.<String>sort(new ArrayList<>());Collections.sort(List, Comparator)当我们想要对不可比较的值进行排序时,我们会使用。Collections.sort(new ArrayList<>(), (String[] a1, String[] a2) -> 0);Collections.<String[]>sort(new ArrayList<>(), (a1, a2) -> 0);当然,您应该用(String[] a1, String[] a2) -> 0真实的比较器替换模拟比较器(它只是将所有元素视为相同)。

慕娘9325324

这里的问题是您没有尝试对字符串列表进行排序(例如,“cat”小于“dog”)。您正在尝试对字符串数组列表进行排序。array["cat", "dog"] 小于 array["dog", "cat"] 吗?默认情况下该逻辑不存在,您必须定义它。示例代码这是一个示例(仅使用第一个元素非常糟糕):public static void main(String[] args) {&nbsp; &nbsp; List<String[]> s = new ArrayList<>();&nbsp; &nbsp; s.add(new String[] {"dog", "cat"});&nbsp; &nbsp; s.add(new String[] {"cat", "dog"});&nbsp; &nbsp; s.sort((o1, o2) -> {&nbsp; &nbsp; &nbsp; &nbsp; //bad example, should check error conditions and compare all elements.&nbsp; &nbsp; &nbsp; &nbsp; return o1[0].compareTo(o2[0]);&nbsp; &nbsp; });&nbsp; &nbsp; //Outputs [cat, dog] then [dog, cat].&nbsp; &nbsp; s.forEach(x -> System.out.println(Arrays.toString(x)));}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java