可以使用Java中的Comparator接口对用户定义类的对象进行排序。java.util.Collections.reverseOrder()方法使用Comparator反转元素集合的顺序。
演示此的程序如下所示-
import java.util.Arrays; import java.util.Collections; import java.util.Comparator; public class Demo { public static void main(String args[]) throws Exception { Comparator comparator = Collections.reverseOrder(); { "John", "Amy", "Susan", "Peter" }; int n = str.length; System.out.println("The array elements are: "); for (int i = 0; i < n; i++) { System.out.println(str[i]); } Arrays.sort(str, comparator); System.out.println("\nThe array elements sorted in reverse order are: "); for (int i = 0; i < n; i++) { System.out.println(str[i]); } } }
上面程序的输出如下-
The array elements are: John Amy Susan Peter The array elements sorted in reverse order are: Susan Peter John Amy
现在让我们了解上面的程序。
比较器与reverseOrder()
方法一起创建。然后定义字符串数组str [],然后使用for循环显示元素。演示这的代码片段如下-
Comparator comparator = Collections.reverseOrder(); { "John", "Amy", "Susan", "Peter" }; int n = str.length; System.out.println("The array elements are: "); for (int i = 0; i < n; i++) { System.out.println(str[i]); }
使用java.util.Arrays.sort()方法以相反的顺序对字符串数组进行排序。然后使用for循环显示数组元素。演示这的代码片段如下-
Arrays.sort(str, comparator); System.out.println("\nThe array elements sorted in reverse order are: "); for (int i = 0; i < n; i++) { System.out.println(str[i]); }