0

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?

1
  • I understand. Can I store this list, and then convert it back into an array? Or is there any easier way to reverse sort an array? Commented Mar 29, 2016 at 13:35

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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));

Comments

0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.