2 回答

TA貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超7個(gè)贊
該方法Collections.sort
的參數(shù)化T
意味著<T extends Comparable<? super T>>
應(yīng)該滿足條件。String[]
不符合要求,因?yàn)樗鼪]有擴(kuò)展Comparable
。
Collections.<String>sort(new ArrayList<>());
Collections.sort(List, Comparator)當(dāng)我們想要對不可比較的值進(jìn)行排序時(shí),我們會(huì)使用。
Collections.sort(new ArrayList<>(), (String[] a1, String[] a2) -> 0);
Collections.<String[]>sort(new ArrayList<>(), (a1, a2) -> 0);
當(dāng)然,您應(yīng)該用(String[] a1, String[] a2) -> 0真實(shí)的比較器替換模擬比較器(它只是將所有元素視為相同)。

TA貢獻(xiàn)1783條經(jīng)驗(yàn) 獲得超4個(gè)贊
這里的問題是您沒有嘗試對字符串列表進(jìn)行排序(例如,“cat”小于“dog”)。您正在嘗試對字符串?dāng)?shù)組列表進(jìn)行排序。
array["cat", "dog"] 小于 array["dog", "cat"] 嗎?默認(rèn)情況下該邏輯不存在,您必須定義它。
示例代碼
這是一個(gè)示例(僅使用第一個(gè)元素非常糟糕):
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)));
}
添加回答
舉報(bào)