Arrays
The Arrays class provides various methods that are useful when working
with arrays. These methods help bridge the gap between collections and arrays.
Each method defined by Arrays is
examined in this section.
The asList( ) method returns a List
that is backed by a specified array. In other words, both the list and the
array refer to the same location. It has the following signature:
static <T> List
asList(T... array)
Here, array is the array that contains the data.
The binarySearch( ) method uses a binary search to find a specified
value. This method must be applied to sorted arrays. Here are some of its
forms. (Additional forms let you search a subrange):
static int binarySearch(byte array[ ], byte value) static int binarySearch(char array[ ], char value)
static int binarySearch(double array[
], double value) static int
binarySearch(float array[ ], float value) static int binarySearch(int array[ ], int value)
static int binarySearch(long array[ ], long value) static int binarySearch(short array[ ], short value) static
int binarySearch(Object array[ ],
Object value)
static <T> int
binarySearch(T[ ] array, T value, Comparator<? super T> c)
Here, array is the array to be searched, and value is the value to be located. The last two forms throw a ClassCastException if array contains elements that cannot be
compared (for example, Double and StringBuffer) or if value is not compatible with the types
in array. In the last form, the Comparator c is used to determine the order of the elements in array. In all cases, if value exists in array, the index of the element is returned. Otherwise, a negative
value is returned.
The copyOf( ) method returns a copy of an array and has the following
forms:
static boolean[ ]
copyOf(boolean[ ] source, int len) static byte[ ] copyOf(byte[ ] source, int len)
static char[ ] copyOf(char[ ]
source, int len) static double[ ] copyOf(double[ ] source, int len) static
float[ ] copyOf(float[ ] source, int len) static int[ ] copyOf(int[ ] source, int len)
static long[ ] copyOf(long[ ]
source, int len) static short[ ] copyOf(short[ ] source, int len) static
<T> T[ ] copyOf(T[ ] source,
int len)
static <T,U> T[ ]
copyOf(U[ ] source, int len, Class<? extends T[ ]> resultT)
The original array is
specified by source, and the length
of the copy is specified by len. If
the copy is longer than source, then
the copy is padded with zeros (for numeric arrays), nulls (for object arrays), or false
(for boolean arrays). If the copy is shorter than source, then the copy is truncated. In the last form, the type of resultT becomes the type of the array
returned. If len is negative, a NegativeArraySizeException is thrown.
If source is null, a NullPointerException
is thrown. If resultT is incompatible with the type of source, an
ArrayStoreException is thrown.
The copyOfRange( ) method returns a copy of a range within an array and
has the following forms:
static boolean[ ]
copyOfRange(boolean[ ] source, int start, int end) static byte[ ] copyOfRange(byte[ ] source, int start, int end)
static char[ ]
copyOfRange(char[ ] source, int start, int end) static double[ ] copyOfRange(double[ ] source, int start, int end) static float[ ] copyOfRange(float[
] source, int start, int end) static
int[ ] copyOfRange(int[ ] source, int
start, int end)
static long[ ]
copyOfRange(long[ ] source, int start, int end) static short[ ] copyOfRange(short[ ] source, int start, int end) static <T> T[ ]
copyOfRange(T[ ] source, int start, int end) static <T,U> T[ ] copyOfRange(U[ ] source, int start, int end,
Class<? extends T[ ]> resultT)
The original array is
specified by source. The range to
copy is specified by the indices passed via start
and end. The range runs from start to end – 1. If the range is longer than source, then the copy is padded with zeros (for numeric arrays), nulls (for object arrays), or false (for boolean arrays). In the last
form, the type of resultT becomes the
type of the array returned. If start
is negative or greater than the length of source,
an ArrayIndexOutOfBoundsException is thrown. If start is greater than end, an IllegalArgumentException is thrown. If source is
null, a NullPointerException is
thrown. If resultT is incompatible with the type of source, an ArrayStoreException is thrown.
The equals( ) method returns true
if two arrays are equivalent. Otherwise, it returns false. The equals( ) method
has the following forms:
static boolean equals(boolean
array1[ ], boolean array2 [ ]) static boolean equals(byte array1[ ], byte array2 [ ])
static boolean equals(char array1[ ], char array2 [ ]) static boolean equals(double array1[ ], double array2
[ ]) static boolean equals(float array1[
], float array2 [ ]) static boolean
equals(int array1[ ], int array2 [ ])
static boolean equals(long array1[ ], long array2 [ ]) static boolean equals(short array1[ ], short array2 [
]) static boolean equals(Object array1[
], Object array2 [ ])
Here, array1 and array2 are the
two arrays that are compared for equality.
The deepEquals( ) method can be used to determine if two arrays, which
might contain nested arrays, are equal. It has this declaration:
static boolean
deepEquals(Object[ ] a, Object[ ] b)
It returns true if the arrays passed in a and b contain the same elements. If a
and b contain nested arrays, then the
contents of those nested arrays are also checked. It returns false if the arrays, or any nested
arrays, differ.
The fill( ) method assigns a value to all elements in an array. In
other words, it fills an array with a specified value. The fill( ) method has two versions. The first version, which has the
following forms, fills an entire array:
static void fill(boolean array[ ], boolean value) static void fill(byte array[
], byte value)
static void fill(char array[ ], char value) static void fill(double array[
], double value) static void
fill(float array[ ], float value) static void fill(int array[ ], int value)
static void fill(long array[ ], long value) static void fill(short array[
], short value) static void
fill(Object array[ ], Object value)
Here, value is assigned to all elements in array. The second version of the fill( ) method assigns a value to a subset of an array.
The sort( ) method sorts an array so that it is arranged in ascending
order. The sort( ) method has two
versions. The first version, shown here, sorts the entire array:
static void sort(byte array[ ]) static void sort(char array[
]) static void sort(double array[ ])
static void sort(float array[ ])
static void sort(int array[ ]) static
void sort(long array[ ])
static void sort(short array[ ]) static void sort(Object array[ ])
static <T> void sort(T array[ ], Comparator<? super T> c)
Here, array is the array to be sorted. In the last form, c is a Comparator that is used to order the elements of array. The last two forms can throw a ClassCastException if elements of the
array being sorted are not comparable. The second version of sort( ) enables you to specify a range
within an array that you want to sort.
JDK 8 adds several new
methods to Arrays. Perhaps the most
important is parallelSort( ) because
it sorts, into ascending order, portions of an array in parallel and then
merges the results. This approach can greatly speed up sorting times. Like sort( ), there are two basic types of parallelSort( ), each with several
overloads. The first type sorts the entire array. It is shown here:
static void parallelSort(byte
array[ ]) static void
parallelSort(char array[ ]) static
void parallelSort(double array[ ])
static void parallelSort(float array[
]) static void parallelSort(int array[
]) static void parallelSort(long array[
]) static void parallelSort(short array[
])
static <T extends
Comparable<? super T>> void parallelSort(T array[ ]) static <T> void parallelSort(T array[ ], Comparator<? super T> c)
Here, array is the array to be sorted. In the last form, c is a comparator that is used to order
the elements in the array. The last two forms can throw a ClassCastException if the elements of the array being sorted are
not comparable. The second version of parallelSort(
) enables you to specify a range within the array that you want to sort.
JDK 8 gives Arrays support for spliterators by
including the spliterator( ) method.
It has two basic forms. The first type returns a spliterator to an entire
array. It is shown here:
static Spliterator.OfDouble
spliterator(double array[ ]) static
Spliterator.OfInt spliterator(int array[
])
static Spliterator.OfLong
spliterator(long array[ ]) static
<T> Spliterator spliterator(T array[
])
Here, array is the array that the spliterator will cycle through. The
second version of spliterator( ) enables
you to specify a range to iterate within the array.
Beginning with JDK 8, Arrays supports the new Stream interface (see Chapter 29) by
including the stream( ) method. It
has two forms. The first is shown here:
static DoubleStream
stream(double array[ ]) static
IntStream stream(int array[ ])
static LongStream stream(long array[ ]) static <T> Stream
stream(T array[ ])
Here, array is the array to which the stream
will refer. The second version of stream( ) enables you to specify a range
within the array.
In addition to those just
discussed, JDK 8 adds three other new methods. Two are related: setAll( ) and parallelSetAll( ). Both assign values to all of the elements, but parallelSetAll( ) works in parallel.
Here is an example of each:
static void setAll(double array[ ],
IntToDoubleFunction<?
extends T> genVal)
static void
parallelSetAll(double array[ ],
IntToDoubleFunction<?
extends T> genVal)
Several overloads exist for
each of these that handle types int,
long, and generic. Finally, JDK 8
includes one of the more intriguing additions to Arrays. It is called
parallelPrefix( ), and it modifies an array so that each element
contains the cumulative result of an
operation applied to all previous elements. For example, if the operation is
multiplication, then on return, the array elements will contain the values
associated with the running product of the original values. It has several
overloads. Here is one example:
static void
parallelPrefix(double array[ ],
DoubleBinaryOperator func)
Here, array is the array being acted upon, and func specifies the operation applied. (DoubleBinaryOperator is a functional interface defined in java.util.function.) Many other
versions are provided, including those that operate on types int, long, and generic, and those that let you specify a range within
the array on which to operate.
Arrays also provides toString( ) and hashCode( ) for the various types of
arrays. In addition, deepToString( ) and deepHashCode( ) are provided, which
operate effectively on arrays that contain nested arrays.
The following program
illustrates how to use some of the methods of the Arrays class:
// Demonstrate Arrays
import java.util.*;
class ArraysDemo {
public static void main(String args[]) {
//Allocate and initialize array.
int array[] = new int[10]; for(int i = 0; i
< 10; i++)
array[i] = -3 * i;
//Display, sort, and display the array.
System.out.print("Original contents:
"); display(array);
Arrays.sort(array);
System.out.print("Sorted: "); display(array);
//Fill and display the array.
Arrays.fill(array, 2, 6, -1);
System.out.print("After fill(): ");
display(array);
//Sort and display the array.
Arrays.sort(array); System.out.print("After
sorting again: "); display(array);
// Binary search for -9.
System.out.print("The value -9 is at
location "); int index =
Arrays.binarySearch(array, -9);
System.out.println(index);
}
static void display(int array[]) { for(int i:
array)
System.out.print(i + " ");
System.out.println();
}
}
The following is the output
from this program:
Original contents: 0 -3 -6 -9 -12 -15 -18 -21
-24 -27
Sorted: -27 -24 -21 -18 -15 -12 -9 -6 -3 0
After fill(): -27 -24 -1 -1 -1 -1 -9 -6 -3 0
After sorting again: -27 -24 -9 -6 -3 -1 -1 -1
-1 0
The value -9 is at location 2
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.