For an array of Objects, the type being sorted must implement the Comparable interface, as shown in Listing 4-2.
Listing 4-2: Sorting objects naturally
@Test
public void sortObjects() {
final String[] strings = {"z", "x", "y", "abc", "zzz", "zazzy"};
final String[] expected = {"abc", "x", "y", "z", "zazzy", "zzz"};
Arrays.sort(strings);
assertArrayEquals(expected, strings);
}
The String class implements the Comparable interface, so the sorting works as you would expect. If the type being sorted does not implement Comparable, this will throw a ClassCastException.
For your own class definitions, you will need to implement Comparable, such as the implementation described in Listing 4-3.
Listing 4-3: Sorting without a Comparable interface
private static class NotComparable {
private int i;
private NotComparable(final int i) {
this.i = i;
}
}
@Test
public void sortNotComparable() {
final List<NotComparable> objects = new ArrayList<>();
for (int i = 0; i < 10; i++) {
objects.add(new NotComparable(i));
}
try {
Arrays.sort(objects.toArray());
} catch (Exception e) {
// correct behavior – cannot sort
return;
}
fail();
}
复制代码
It is not possible to use the Collections.sort method because the compiler expects the type of the parameter to be an implementation of Comparable. The method signature is:
public static <T extends Comparable<? super T>> void sort(List<T> list)
If you want to provide your own ordering, you provide an implementation of the Comparator interface to the sort method. This interface has two methods: int compare(T o1, T o2) for the implementing type T, and boolean equals(Object o). The compare method returns an int in one of three states: negative if the first argument is sorted before the second, zero if the two are equal, or positive if the second argument is sorted first.