Arrays.sort(arr, Collections.reverseOrder());
时间: 2024-04-20 19:26:06 浏览: 20
这是一个常见的 Java 代码片段,用于对数组进行降序排序。它使用了 `Arrays.sort()` 方法和 `Collections.reverseOrder()` 方法。
`Arrays.sort(arr)` 会对数组 `arr` 进行升序排序。但是,通过使用 `Collections.reverseOrder()` 方法作为参数,可以将排序顺序反转,从而实现降序排序。
请注意,这段代码假设数组 `arr` 的元素类型是可进行比较的。如果元素类型不是基本类型或实现了 `Comparable` 接口,可能会抛出异常。
相关问题
Arrays.sort
Arrays.sort is a built-in method in Java that is used to sort arrays of primitive data types and objects. It sorts the elements of an array in ascending order by default, but can also sort in descending order if a custom comparator is provided.
Syntax:
There are two overloaded versions of the sort() method:
1. For sorting arrays of primitive data types:
public static void sort(type[] arr)
2. For sorting arrays of objects:
public static void sort(Object[] arr)
Examples:
1. Sorting an array of integers in ascending order:
int[] arr = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr)); // prints [1, 1, 2, 3, 3, 4, 5, 5, 6, 9]
2. Sorting an array of strings in descending order:
String[] arr = {"apple", "banana", "cherry", "date"};
Arrays.sort(arr, Collections.reverseOrder());
System.out.println(Arrays.toString(arr)); // prints [date, cherry, banana, apple]
Note: The reverseOrder() method is used to create a comparator that sorts elements in reverse order.
java Arrays.sort()
Java中可以使用Arrays.sort()方法对数组进行排序,如果要对数组进行倒序排序,可以使用Collections.reverseOrder()方法来实现。
具体实现方法如下:
1. 定义一个数组arr,例如int[] arr = {3, 1, 4, 2, 5};
2. 使用Arrays.sort()方法对数组进行排序,例如Arrays.sort(arr);
3. 使用Collections.reverseOrder()方法对数组进行倒序排序,例如Arrays.sort(arr, Collections.reverseOrder());
4. 最终得到的数组arr为{5, 4, 3, 2, 1},即为倒序排列后的结果。
需要注意的是,如果数组中的元素类型是自定义的类,需要实现Comparable接口并重写compareTo()方法,或者使用Comparator接口来进行排序。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)