2 回答
TA贡献1895条经验 获得超7个赞
该方法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真实的比较器替换模拟比较器(它只是将所有元素视为相同)。
TA贡献1783条经验 获得超4个赞
这里的问题是您没有尝试对字符串列表进行排序(例如,“cat”小于“dog”)。您正在尝试对字符串数组列表进行排序。
array["cat", "dog"] 小于 array["dog", "cat"] 吗?默认情况下该逻辑不存在,您必须定义它。
示例代码
这是一个示例(仅使用第一个元素非常糟糕):
public static void main(String[] args) {
List<String[]> s = new ArrayList<>();
s.add(new String[] {"dog", "cat"});
s.add(new String[] {"cat", "dog"});
s.sort((o1, o2) -> {
//bad example, should check error conditions and compare all elements.
return o1[0].compareTo(o2[0]);
});
//Outputs [cat, dog] then [dog, cat].
s.forEach(x -> System.out.println(Arrays.toString(x)));
}
添加回答
举报