Java Reference
In-Depth Information
33
34
// compare intArray and filledIntArray for equality
35
b = Arrays.equals(intArray, filledIntArray);
36
System.out.printf(
"intArray %s filledIntArray%n"
,
37
(b ?
"=="
:
"!="
));
38
39
// search intArray for the value 5
40
int
location = Arrays.binarySearch(intArray,
5
);
41
42
if
(location >=
0
)
43
System.out.printf(
44
"Found 5 at element %d in intArray%n"
, location);
45
else
46
System.out.println(
"5 not found in intArray"
);
47
48
// search intArray for the value 8763
49
location = Arrays.binarySearch(intArray,
8763
);
50
51
if
(location >=
0
)
52
System.out.printf(
53
"Found 8763 at element %d in intArray%n"
, location);
54
else
55
System.out.println(
"8763 not found in intArray"
);
56
}
57
58
// output values in each array
59
public static
void
displayArray(
int
[] array, String description)
60
{
61
System.out.printf(
"%n%s: "
, description);
62
63
for
(
int
value : array)
64
System.out.printf(
"%d "
, value);
65
}
66
}
// end class ArrayManipulations
doubleArray: 0.2 3.4 7.9 8.4 9.3
filledIntArray: 7 7 7 7 7 7 7 7 7 7
intArray: 1 2 3 4 5 6
intArrayCopy: 1 2 3 4 5 6
intArray == intArrayCopy
intArray != filledIntArray
Found 5 at element 4 in intArray
8763 not found in intArray
Fig. 7.22
|
Arrays
class methods and
System.arraycopy
. (Part 2 of 2.)
Line 19 calls
static
method
fill
of class
Arrays
to populate all 10 elements of
filledIntArray
with
7
s. Overloaded versions of
fill
allow you to populate a specific
range of elements with the same value. Line 20 calls our class's
displayArray
method
(declared at lines 59-65) to output the contents of
filledIntArray
.
Line 25 copies the elements of
intArray
into
intArrayCopy
. The first argument
(
intArray
) passed to
System
method
arraycopy
is the array from which elements are to