About Privacy Need Help NOW?

Articles


Code:

View

Download

Descending Object Arrays

Joe Sam Shirah


     Descending Arrays discussed several ways to sort both primitive and object arrays. All of the methods mentioned there manipulate the array after it has been sorted into ascending order. For arrays containing Objects rather than primitives, there is another way that the java.util.Arrays class can handle. While it involves writing a new class for each type, the class only needs to be written once. For most object types the required class can be very small with almost identical code in each class.

     JDK 1.2 introduced the java.lang.Comparable and java.util.Comparator interfaces. Most objects in the JDK now implement Comparable, whose only method is compareTo(Object o). The Comparator interface requires compare(Object o1, Object o2) and equals(Object obj) implementations. Most of the time, java.lang.Object.equals(Object obj) will suffice, and we're just going to assume that for the purposes of this article.

     Comparable is implemented by an object to compare itself to another object. Comparator is used to compare two distinct objects, whether related to the implementing object or not. Both Comparable.compareTo() and Comparator.compare() return an integer. The value returned is either negative, zero, or positive. The meaning is the result of comparing the *this* object against the object sent for Comparable, and o1 against o2 for Comparator - let's call *this* and o1 the compared object, and the sent object and o2 the comparison object.

     Respectively, negative means that the the compared object is less than the comparison object, zero means they are the same, and positive means that the compared object is greater than the comparison object. These results can also be used for sorts as well as for simple comparisons.

     Now let's go back to the java.util.Arrays class, which has two methods of interest. sort(Object[] a) works with objects that implement Comparable, and sort(Object[] a, Comparator c) obviously makes use of a Comparator. These, especially objects with a Comparable implementation, are generally for ascending orders. However, with just a little work, we can create a descending Comparator.

     It's probably blindingly obvious, particularly after reading Descending Arrays, that descending order is just the reverse of ascending order. We can extend this notion to Comparators by reversing the result of the value returned from Comparable.compareTo(). For example: return -( myString.compareTo( anotherString ) ); Easy to code, and that's exactly what we've done for a descending String Comparator in this article's code example.

     The same concept can be applied to any object that implements Comparable, with nearly identical code. Check it out and, !gnitros yppaH



Copyright © 2000-2003, conceptGO