Comparable Interface

Objects that have an ordering are compared using the compareTo() method.

13. Ordered Array


ComparisonZero, Negative, or Positive
" 9999".compareTo("023")negative
"More Cheese?".compareTo("More Cheese!")positive

Ordered Array


The elements of an ordered array are arranged in ascending (or descending) order. In general, an ordered array can have duplicate elements. (In some situations, though, an array is guaranteed not to have duplicates.) The picture shows an array of ints arranged into ascending order.

The elements of an array can be arranged in order by using a static sort() method of the Arrays class.

// Sort the array into ascending order
static void sort( array )

There are sort() methods for arrays of type byte[] , char[] , double[] , float[] , int[], and long[]. There is also a method that can sort object references based on the values of the objects.

Sorting is an important process in computer programming. Many data processing operations depend on data that is sorted, much as the data in a filing cabinet is kept sorted.

Question 13:

Would a dictionary be useful if its definitions were not in sorted order?