KOB
KOB

Reputation: 4545

Sorting an array in reverse order - not reversing

I am trying to sort an array of integers from highest to lowest.

int[] array = {2, 6, 4, 1};    
Arrays.sort(array);
Collections.reverse(Arrays.asList(array));
for (int num : array) {
    System.out.println(num);
}

This prints the array in an ascending order - 1, 2, 4, 6. Why is it not being reversed, or why is the array not being permanently stored in its reversed state?

Upvotes: 0

Views: 535

Answers (3)

Mirko Stocker
Mirko Stocker

Reputation: 2242

There are several problems in your code: Arrays.asList does not create a new List<Integer>, it's actually a List<int[]>. But even if it worked as you expected, the returned list is only a temporary object, you're still printing the array.

Unfortunately, the correct solution is not very elegant:

int[] array = {2, 6, 4, 1};    
Arrays.sort(array);
List<Integer> asList = new ArrayList<Integer>(); 
for(int i : array) {
    asList.add(i);
}
Collections.reverse(asList);
for (int num : asList) {
    System.out.println(num);
}

Upvotes: 0

SomeJavaGuy
SomeJavaGuy

Reputation: 7347

The most "easy" solution would be to use the reverseComperator provided by the Collections class. This will automaticly sort the array in a descending order.

public static void main(String[] args) {
    // Use the Wrapper class, otherwise you can´t call Arrays.sort with a comperator.
    Integer[] array = {2, 6, 4, 1};
    Arrays.sort(array, Collections.reverseOrder());
    for (int num : array) {
        System.out.println(num);
    }
}

As why your solution doesn´t work.
You temporarly create a List with Arrays.asList(array), which you do reverse and that isn´t refered to anymore afterwards. This wont change the order for the array variable.

Upvotes: 2

Austin
Austin

Reputation: 8575

You're displaying the result of sorting the array, not the result of reversing the list. You would need to store the sorted list in a temporary variable, reverse it, then call toArray to get the desired behavior.

The more straightforward way to sort in reverse order is to do:

Arrays.sort(array, (o1,o2)-> Integer.compare(o2,o1));

Upvotes: 0

Related Questions