Java Reference
In-Depth Information
This sets the first 50 elements to reference one Person object and the second 50 elements to reference
another.
Copying an Array
You can copy an array of any type using the static copyOf() method in the Arrays class. Here's an example:
String[] decisions = {"yes", "no", "maybe", "definitely not"};
String[] copyDecisions = Arrays.copyOf(decisions, decisions.length);
copyDecisions references a new array that is returned by the copyOf() method that is a duplicate of
decisions because the second argument specifies the same length as decisions. If the second argument
to copyOf() is negative, a NegativeArraySizeException is thrown. If the first argument is null , a
NullPointerException is thrown. Both exceptions have RuntimeException as a base class and therefore
need not be caught.
You can arrange for the array copy to be truncated, or to have an increased number of elements by spe-
cifying a different value for the second argument. For example:
String[]copyDecisions1 = Arrays.copyOf(decisions, decisions.length - 2);
String[]copyDecisions2 = Arrays.copyOf(decisions, decisions.length + 5);
Here copyDecisions1 has just two elements corresponding to the first two elements of decisions . The
copyDecisions2 array has nine elements. The first four are identical to that of the first argument, de-
cisions , and the last five are set to null .
You can also create a new array from part of an existing array. For example:
String[]copyDecisions = Arrays.copyOfRange(decisions, 1, 3);
The new array that is created contains two elements, "no" and "maybe" . The second and third arguments
specify the index values for the first element to be copied and one beyond the last element to be copied
respectively. The second argument must be between zero and the length of the array that is the first argu-
ment, otherwise an ArrayIndexOutOfBoundsException is thrown. If the second argument is not less than
the third argument, an IllegalArgumentException is thrown. The third argument can be greater than the
length of the array being copied, in which case the excess elements are supplied as the equivalent of null —
that is, null for an array containing objects and zero for numerical elements. If the first argument is null , a
NullPointerException is thrown. All the exceptions that the copyOfRange() method can throw are sub-
classes of RuntimeException so you are not obliged to catch them.
Comparing Arrays
There are nine overloaded versions of the static equals() method for comparing arrays defined in the Ar-
rays class, one for each of the types that apply to the fill() method. All versions of equals() are of the
form:
boolean equals( type [] array1, type [] array2)
Search WWH ::




Custom Search