我想对 ArrayList
进行排序的ArrayList<Integer>
,看起来像。
ArrayList<ArrayList<Integer>> allres = new ArrayList<ArrayList<Integer>>();
Collections.sort(allres, new Comparator<ArrayList<Integer>>() {
public int compare(ArrayList<Integer> a, ArrayList<Integer> b) {
for (int i = 0; i < a.size(); i++) {
if (a.get(i) < b.get(i)) {
return -1;
} else if (a.get(i) == b.get(i)) {
continue;
} else {
return 1;
}
}
return -1;
}
});
但是对于某些输入,它没有给出字典排序的结果。
最佳答案
包含 1
或 -1
的比较器函数容易出错。
相反,你应该这样写:
public static int lexicographically(List<Integer> a, List<Integer> b) {
for (int i = 0, end = Math.min(a.size(), b.size()); i < end; i++) {
int res = Integer.compare(a.get(i), b.get(i));
if (res != 0)
return res;
}
return Integer.compare(a.size(), b.size());
}
这种比较器函数的编写风格可以防止各种常见错误,例如从不返回 0。
这种风格中最重要的模式是:
- 按照第一个标准进行比较。
- 如果给定值不同,则返回比较结果并完成。
- 采用下一个标准,继续第 1 步。
- 如果没有剩余条件,则返回 0。
关于java - java中Arraylist<Integer>的ArrayList的字典排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55312543/