Arrays Class

Package: java.util

The Arrays class provides a collection of static methods that are useful for working with arrays.

For more information about arrays, see Arrays in Part 2.

Because the Arrays class provides only static methods, it has no constructors.

Methods

Method

Description

static int binarySearch ( array, key)

Searches for the specified key value in an array. The return value is the index of the element that matches the key. The method returns -1 if the key can’t be found. The array and the key must be of the same type and can be any primitive type or an object.

static array copyOf (arrayOriginal, newLength)

Returns an array that’s a copy of arrayOriginal. The newLength parameter need not equal the original array’s length. If newLength is larger, the method pads the new array with zeros. If newLength is smaller, the method doesn’t copy all of the original array’s values.

static array copyOfRange (arrayOriginal, from, to)

Does what the copyOf method does, but copies only a selected slice of values (from one index to another) of the original array.

boolean deepEquals( array1, array2)

Returns true if the two arrays have the same element values. This method works for arrays of two or more dimensions.

boolean equals( array1, array2)

Returns true if the two arrays have the same element values. This method checks equality only for one-dimensional arrays.

static void fill( array, value)

Fills the array with the specified value. The value and array must be of the same type and can be any primitive type or an object.

static void fill( array, from, to, value)

Fills the elements indicated by the from and to int parameters with the specified value. The value and array must be of the same type and can be any primitive type or an object.

static void sort( array)

Sorts the array in ascending sequence.

static void sort( array, from, to)

Sorts the specified elements of the array in ascending sequence.

static String toString( array)

Formats the array values in a string. Each element value is enclosed in brackets, and the element values are separated with commas.

Filling an array

The fill method lets you prefill an array with values other than the default values for the array type. Here’s a routine that creates an array of integers and initializes each element to 100:

int[] startValues = new int[10];

Arrays.fill(startValues, 100);

Although you can code a complicated expression as the second parameter, the fill method evaluates this expression only once. Thus, every element in the array is assigned the same value when you use the fill method.

Copying an array

The copyOf and copyOfRange methods let you copy multiple elements from an existing array into a new array. If you start with something named arrayOriginal, for example, you can copy the arrayOriginal elements to something named arrayNew like this:

int arrayOriginal[] = {42, 55, 21};

int arrayNew[] = Arrays.copyOf(arrayOriginal, 3);

In the preceding example, the arrayNew will have three elements (42, 55, and 21) just like arrayOriginal.

If the second parameter is less than the number of elements in the original array, the new array is truncated. For example:

int arrayNew[] = Arrays.copyOf(arrayOriginal, 2);

results in an array that has two elements (42 and 55).

If the second parameter is greater than the number of elements in the original array, the new array contains additional elements, padded with default values. For example:

int arrayNew[] = Arrays.copyOf(arrayOriginal, 4);

results in an array with four (42, 55, 21, and 0).

The copyOfRange method lets you specify the starting and ending element index. For example:

int arrayOriginal[] = {42, 55, 21, 16, 100, 88};

int arrayNew[] = Arrays.copyOfRange(arrayOriginal, 2, 5);

results in an array with three elements (21, 16, and 100).

Sorting an array

The sort method is a quick way to sort an array in sequence. These statements create an array with 100 random numbers and then sort the array in sequence so that the random numbers are in order:

int[] lotto = new int[6];

for (int i = 0; i < 6; i++)

lotto[i] = (int)(Math.random() * 100) + 1;

Arrays.sort(lotto);

Searching an array

The binarySearch method is an efficient way to locate an item in an array by its value. Suppose that you want to find out whether your lucky number is in the lotto array created in the preceding example. You could just use a for loop to search the array from beginning to end. But for large arrays, that can be inefficient. The binarySearch method can search large arrays more quickly:

int lucky = 13;

int foundAt = Arrays.binarySearch(lotto, lucky);

if (foundAt > -1)

System.out.println(“My number came up!”);

else

System.out.println(“I’m not lucky today.”);

Note that to use the binarySearch method, the array must be sorted.

TechnicalStuff.eps The binarySearch method uses a technique similar to the strategy for guessing a number. If I say that I’m thinking of a number between 1 and 100, you don’t start guessing the numbers in sequence starting with 1. Instead, you guess 50. If I tell you that 50 is low, you guess 75. If I tell you that 75 is high, you guess halfway between 50 and 75, and so on until you find the number. The binarySearch method uses a similar technique, but it works only if the array is sorted first.

Comparing arrays

If you use the equality operator (==) to compare array variables, the array variables are considered equal only if both variables point to exactly the same array instance. To compare two arrays element by element, you should use the Arrays.equal method instead. For example:

if (Arrays.equal(array1, array2))

System.out.println(“The arrays are equal!”);

In this example, arrays array1 and array2 are compared element by element. If both arrays have the same number of elements, and all elements have the same value, the equals method returns true. If the elements are not equal, or if one array has more elements than the other, the equals method returns false.

tip.eps If the array has more than one dimension, you can use the deepEquals method instead. It compares any two subarrays, element by element, to determine whether they’re identical.

Converting arrays to strings

The toString method of the Arrays class is handy if you want to quickly dump the contents of an array to the console to see what it contains. This method returns a string that shows the array’s elements enclosed in brackets, with the elements separated by commas.

Here’s a routine that creates an array, fills it with random numbers, and then uses the toString method to print the array elements:

int[] lotto = new int[6];

for (int i = 0; i < 6; i++)

lotto[i] = (int)(Math.random() * 100) + 1;

System.out.println(Arrays.toString(lotto));

Here’s a sample of the console output created by this code:

[4, 90, 65, 84, 99, 81]

Note that the toString method works only for one-dimensional arrays. To print the contents of a two-dimensional array with the toString method, use a for loop to call the toString method for each subarray.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset