基本用法

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 + " ");
}
}
//输出: 1 1 3 3 4 6 8 48 54

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};
//对a[3] - a[6]排序
Arrays.sort(a,3,7);
for (int c : a) {
System.out.print(c + " ");
}
}
//输出:4 6 1 1 3 8 48 3 54

自定义排序

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) {
//返回值>0 交换
return o2 - o1;
// 不建议上面的这种写法,这样写容易超出 Integer.MAX_VALUE ,下面的写法更好
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};
//(Comparator<Integer>) 可省略
Arrays.sort(a, (Comparator<Integer>) (o1, o2) -> o2 > o1 ? 1 : -1;);
}

Arrays.sort() 和 C++ 中的sort() 的区别

Arrays.sort() 自定义排序时,返回值 >0 交换二个元素的位置。C++ 中的 sort() 与之相反。

评论




博客内容遵循 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议

载入天数...载入时分秒... 本站使用 Volantis 作为主题 鲁ICP备-20012065号