Possible Duplicate:
Sort ArrayList of custom Objects by property
How do i sort array elements into ascending order?
Possible Duplicate:
Sort ArrayList of custom Objects by property
How do i sort array elements into ascending order?
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()
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]"
From java.util.Arrays
:
Arrays.sort(...)
Reference: https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Arrays.html