基本用法
Arrays.sort(int[] a)
对数组 a 中所有元素按从小到大的顺序排序。
1 2 3 4 5 6 7 8
| public static void main(String[] args) { int[] a = {4, 6, 1, 8, 1, 3, 48, 3, 54}; Arrays.sort(a); for (int c : a) { System.out.print(c + " "); } }
|
Arrays.sort(int[] a,int fromIndex,int toIndex)
对数组 a 中的下标从 formIndex 到 toIndex - 1 的元素按从小到大的顺序排序。
1 2 3 4 5 6 7 8 9
| public static void main(String[] args) { int[] a = {4, 6, 1, 8, 1, 3, 48, 3, 54}; Arrays.sort(a,3,7); for (int c : a) { System.out.print(c + " "); } }
|
自定义排序
Arrays.sort(int[] a,Comparator<? Super T> c) 用Comparator借口实现自定义排序。
1 2 3 4 5 6 7 8 9 10 11 12
| public static void main(String[] args) { Integer[] a = {4, 6, 1, 8, 1, 3, 48, 3, 54}; Arrays.sort(a, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2 - o1; return o2 > o1 ? 1 : -1; } }); }
|
和下面的写法等价
1 2 3 4 5
| public static void main(String[] args) { Integer[] a = {4,6,1,8,1,3,48,3,54}; Arrays.sort(a, (Comparator<Integer>) (o1, o2) -> o2 > o1 ? 1 : -1;); }
|
Arrays.sort() 和 C++ 中的sort() 的区别
Arrays.sort() 自定义排序时,返回值 >0 交换二个元素的位置。C++ 中的 sort() 与之相反。