Class Arrays
In the java.util package there is a class called Arrays that
contains various methods for manipulating arrays. The methods that
you will find useful are:
- binarySearch ( array, key ) - searches the specified array for the
key using the binary search algorithm.
- equals ( array1, array2 ) - returns the boolean value true
if array1 is equal to array2, otherwise it returns false.
- fill ( array, value ) - fills the specified array with the specified
value.
- sort ( array ) - sorts the given array
I have appended a piece of code that shows how to use the methods in
this class. Do not forget to use the import statement in your program.
import java.util.*;
public class TestArray
{
// This method prints an array
public static void printArray ( int[] anArray )
{
for ( int i = 0; i < anArray.length; i++ )
System.out.print ( anArray[i] + " " );
System.out.println ();
}
public static void main ( String [] args )
{
// Create an array and print it
int[] intArray = { 87, 23, 67, 46, 91, 52 };
printArray ( intArray );
// Sort the array and print it
Arrays.sort ( intArray );
printArray ( intArray );
// Search for an item in the array
int x = 46;
int i = Arrays.binarySearch ( intArray, x );
System.out.println ( "The number " + x + " is at " + i );
// Search for an item not in the array
x = 73;
i = Arrays.binarySearch ( intArray, x );
System.out.println ( "The number " + x + " is at " + i );
// Create another array and test if they are equal
int[] intArray2 = { 87, 67, 23, 46, 91, 52 };
if ( Arrays.equals ( intArray, intArray2 ) )
System.out.println ( "The arrays are equal.");
else
System.out.println ( "The arrays are not equal." );
// Print the array, fill it with a specified value and print it
// again to verify
printArray ( intArray2 );
Arrays.fill ( intArray2, -1 );
printArray ( intArray2 );
}
}