Java Reference
In-Depth Information
useful if you need to sort classes that you cannot re-write to implement the
comparable interface. The Comparator class has two methods:
int compare (Object obj1, Object obj2)
boolean equals (Object obj1, Object obj2)
The compare() method should return a negative, zero, or positive integer,
according to the ordering rules that you implement, if obj1 is less than, equal to,
or greater than obj2 . Similarly, the equals() method compares the objects for
equality according to the rules you implement. When using the Comparator
technique, the two object array sorting methods are:
void sort (Object[] array, Comparator comp)
void sort (Object[] array, int fromIndex, int toIndex,
Comparator comp)
Another useful set of overloaded methods in the Arrays class is the set of binary
searching methods:
int binarySearch ( type [] array, type key)
int binarySearch (Object[] array, Object key,
Comparator comp)
There is an overloaded binarySearch() method for each primitive type except
boolean and one more for Object . These methods search an array for the given
keyvalue. The array to be searched must be sorted first in ascending order, perhaps
by using one of the sort() methods just discussed. The methods return the index
to the position where the key is found, or if it is not found, to the insertion point.
The insertion point is the place in the array where all the elements are less than
the key and all the elements above it are greater than or equal to it. The methods
return array.length() if all elements are less than the key.
For the case of Object arrays and the first type of binarySearch()
method above, the elements must implement the Comparable interface. If you
cannot change the classes to implement this interface, then you can provide a
Comparator and use the second type of binarySearch() method shown
above.
10.10.4 Arrays.toString()
One small, but extremely useful, addition to J2SE 5.0 is the static
Arrays.toString() method. It conveniently returns a string representation
of the contents of an array. Consider the now familiar public static void
main (String[] args) method. Almost anyone who has used Java for any
time has written a loop like the following to echo the input parameters:
for (int i = 0; i < args.length; i++)
System.out.println (args[i] + " , " );
Search WWH ::




Custom Search