|
Do you need help with your Java programming?
Click here for instant help with your Java code. |
Sorting an Array in Descending (Reverse) Order
The Arrays class can be used to sort an array of either reference types or primitive types, but the Arrays class does have an overloaded sort method that can sort an array in any way we choose. That overloaded variant of the sort method can only take reference types, and it has an additional parameter which is of type Comparator. This is the parameter that tells how we want the array sorted. In the example below we call the static method reverseOrder on the Collections class. It returns a Comparator instance which will sort the array descending instead of normal ascending. Since this overloaded sort method only take reference types, we have to use the proper wrapper class (in this case Integer) if we want to work with primitive types. |
package com.javadb.examples; import java.util.Arrays; import java.util.Collections; /** * * @author www.javadb.com */ public class Main { /** * Example method for sorting an Integer array * in reverse order. */ public void sortIntArrayReverseOrder() { Integer[] arrayToSort = new Integer[] { new Integer(48), new Integer(5), new Integer(89), new Integer(80), new Integer(81), new Integer(23), new Integer(45), new Integer(16), new Integer(2) }; Arrays.sort(arrayToSort, Collections.reverseOrder()); for (Integer i : arrayToSort) { System.out.println(i.intValue()); } } /** * @param args the command line arguments */ public static void main(String[] args) { Main main = new Main(); main.sortIntArrayReverseOrder(); }} |
The output: |
89 81 80 48 45 23 16 5 2 |
| Do you know your Java? | |
| Take a Ten-Question-Java-Quiz! | |
Search for code examples on this site
