Java Reference
In-Depth Information
Table 7.2
Useful Methods of the
Arrays
Class
Method
Description
returns a copy of the array with the given size
copyOf(array, newSize)
returns a copy of the given subportion of the given array
copyOfRange(array,
from
startIndex
(inclusive) to
endIndex
(exclusive)
startIndex, endIndex)
returns
true
if the arrays contain the same elements
equals(array1, array2)
sets every element of the array to be the given value
fill(array, value)
rearranges the elements so that they appear in sorted
(nondecreasing) order
sort(array)
returns a
String
representation of the array, as in
[3, 5, 7]
toString(array)
The third limitation is that you can't compare arrays for equality using a simple
==
test. We saw that this was true of
String
s as well. If you want to know whether two
arrays contain the same set of values, you should call the
Arrays.equals
method:
int[] data1 = {1, 1, 2, 3, 5, 8, 13, 21};
int[] data2 = {1, 1, 2, 3, 5, 8, 13, 21};
if (Arrays.equals(data1, data2)) {
System.out.println("They store the same data");
}
This code prints the message that the arrays store the same data. It would not do so
if we used a direct comparison with
==
.
The
Arrays
class provides other useful methods as well, including methods for
sorting the array and for filling it up with a specific value. Table 7.2 contains a list of
some of the most useful methods in the
Arrays
class.
The previous section presented two standard patterns for manipulating an array. The
first is the traversing loop, which uses a variable of type
int
to index each array
value:
for (int i = 0; i < <array>.length; i++) {
<do something with array[i]>;
}
The second is the for-each loop:
for (<type> <name> : <array>) {
<statement>;
<statement>;
Search WWH ::
Custom Search