Array Utilities

   

Array Utilities

The java.util package focuses on supporting the collections framework classes, but the simple array is not overlooked either. The Arrays class provides a number of static methods useful in manipulating arrays just as the Collections class supports the more sophisticated containers.

The Arrays Class

The Arrays class consists solely of static methods that operate on an array, or compare two arrays for equality. Nearly all the methods are for searching, comparing, filling, or sorting an array. The one exception is the asList method, which provides a List view of an underlying array:

 public static List asList(Object[] a) 

You can iterate an array using the reference returned by asList and even modify the array through the List methods if desired.

Searching an Array

The Arrays class defines nine overloaded versions of its binarySearch method. You can use one of these methods to efficiently locate a specific primitive value or object within an array. In general, the signature of each method expects an array of a specific data type followed by a value or object to locate. Before using one of these methods, you must sort the array into ascending order or its natural order, or apply a Comparator to it. The sort methods defined by the class make this easy to do.

Comparing Two Arrays

The nine overloaded equals methods compare two arrays for equality and return a boolean result. For two arrays to be considered equal, they must contain the same elements in the same order. The overloaded methods support each of the primitive types and Object.

Filling an Array

The fill methods assign a single value or object to either every element in an array or a range that you specify. The 18 overloaded versions support full or partial filling for each of the primitive types and Object.

Sorting an Array

Similar to fill, Arrays provides 18 versions of its sort method to support sorting an array of primitives or Object. You have the option of sorting an entire array or only a specific range of elements.

   


Special Edition Using Java 2 Standard Edition
Special Edition Using Java 2, Standard Edition (Special Edition Using...)
ISBN: 0789724685
EAN: 2147483647
Year: 1999
Pages: 353

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net