Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Reverse sort of array  RSS feed

 
E Ni
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there anyway to sort an array in reverse order?
I tried using Arrays.sort() but this sorts in ascending order but can you do this for descending order?
 
Nathaniel Stoddard
Ranch Hand
Posts: 1258
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It looks like it depends on what is in the array. If the elements of the array are primitives, then you're stuck. However, if they are Objects, then you can use sort(array, comparator), where comparator is an object that implements the Comparator interface, sorting it in whatever order you want.
(This is all in the API docs for java.util.Arrays).
 
E Ni
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Its an array of integers. Is there any way I can sort this?
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's a round-about way of doing it
 
Blake Minghelli
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's another possibility...
 
Wayne L Johnson
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or you could sort them (in ascending order) and then call the "Collections.reverse()" method to reverse them.
[ADDED]This would require converting the Array to ArrayList, do the sort and "reverse()", and then convert it back to an Array.
[ March 10, 2004: Message edited by: Wayne L Johnson ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!