Java Reference
In-Depth Information
12.
13. Arrays.sort(values);
14.
15. System.out.print(“\nSorted values: “);
16. for(int i : values) {
17. System.out.print(i + “ “);
18. }
The previous code breakdowns as follows:
1. Line 6 creates an array of 15 int s named values .
2. The for loop on line 8 fills the array with random numbers between 0 and 9 and
displays those values.
3. Line 13 sorts the values array. Because the array is of type int , the array is ordered in
its natural ordering.
4. The for loop on line 16 displays the array again.
Here is a sample output of the previous code:
Initial values: 8 0 7 9 9 9 0 5 7 1 5 0 9 3 8
Sorted values: 0 0 0 1 3 5 5 7 7 8 8 9 9 9 9
The array is sorted in its natural order, which for int s is numerical order. Now let's
look at an example where a Comparator is used to determine the sort order. See if you can
determine the ordering logic of the following comparator:
public class EvenSorter implements java.util.Comparator<Integer> {
public int compare(Integer a, Integer b) {
return (b%2) - (a%2);
}
}
If a and b are equal, the compare method returns 0 . If both numbers are even or odd, the
return value is also 0 , so two even numbers are equal and two odd numbers are equal. If
a is even and b is odd, the result is 1 , so even numbers are greater than odd numbers. The
following code sorts an array of random Integer objects using an EvenSorter comparator:
Integer [] values = new Integer[15];
System.out.print(“Initial values: “);
for(int i = 0; i < values.length; i++) {
values[i] = (int) (Math.random() * 10);
System.out.print(values[i] + “ “);
}
Arrays.sort(values, new EvenSorter());
Search WWH ::




Custom Search