0

Possible Duplicate:
Sort ArrayList of custom Objects by property

How do i sort array elements into ascending order?

Community
  • 1
  • 1
  • Is this a primitive array, e.g. "String t[0]", or a Collections array, e.g. "List t = new ArrayList()"? – seanhodges May 10 '10 at 07:49
  • http://www.google.com/search?hl=en&source=hp&q=java+sort+arrays+descending+order&btnI=I'm+Feeling+Lucky&aq=f&aqi=&aql=&oq=&gs_rfai=%20HTTP/1.1 – msw May 10 '10 at 08:36

3 Answers3

3

Your elements must be Comparable or use a Comparator that compares the objects in the array. This is needed, as Java doesn't know by which fields you want to compare two objects. An OK example seems to be the following: http://lkamal.blogspot.com/2008/07/java-sorting-comparator-vs-comparable.html

After that you can use Array.sort()

Indrek
  • 6,516
  • 4
  • 29
  • 27
2

You use an overload of sort from java.util.Arrays that works in your case; you may need to implement Comparable or provide a custom Comparator, or neither if your type is a primitive/already defines its own natural ordering.

    int[] arr = { 3, 1, 5, 7, 2, -5 };
    Arrays.sort(arr);
    System.out.println(Arrays.toString(arr));
    // prints "[-5, 1, 2, 3, 5, 7]"

See also

Community
  • 1
  • 1
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
0

From java.util.Arrays:

Arrays.sort(...)

Reference: https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Arrays.html

UkFLSUI
  • 5,509
  • 6
  • 32
  • 47
Jarle Hansen
  • 1,993
  • 2
  • 16
  • 29