Java Reference
In-Depth Information
Class
Arrays
helps you avoid reinventing the wheel by providing
static
methods for
common array manipulations. These methods include
sort
for
sorting
an array (i.e., ar-
ranging elements into ascending order),
binarySearch
for
searching
a
sorted
array (i.e., de-
termining whether an array contains a specific value and, if so, where the value is located),
equals
for
comparing
arrays and
fill
for
placing values into an array
. These methods are
overloaded for primitive-type arrays and for arrays of objects. Our focus in this section is
on using the built-in capabilities provided by the Java API. Chapter 19, Searching, Sorting
and Big O, shows how to implement your own sorting and searching algorithms, a subject
of great interest to computer-science researchers and students.
Figure 7.22 uses
Arrays
methods
sort
,
binarySearch
,
equals
and
fill
, and shows
how to
copy
arrays with class
System
's
static
arraycopy
method
. In
main
, line 11 sorts
the elements of array
doubleArray
. The
static
method
sort
of class
Arrays
orders the
array's elements in
ascending
order by default. We discuss how to sort in
descending
order
later in the chapter. Overloaded versions of
sort
allow you to sort a specific range of ele-
ments within the array. Lines 12-15 output the sorted array.
1
// Fig. 7.22: ArrayManipulations.java
2
// Arrays class methods and System.arraycopy.
3
import
java.util.Arrays;
4
5
public class
ArrayManipulations
6
{
7
public static void
main(String[] args)
8
{
9
// sort doubleArray into ascending order
10
double
[] doubleArray = {
8.4
,
9.3
,
0.2
,
7.9
,
3.4
};
11
Arrays.sort(doubleArray);
12
System.out.printf(
"%ndoubleArray: "
);
13
14
for
(
double
value : doubleArray)
15
System.out.printf(
"%.1f "
, value);
16
17
// fill 10-element array with 7s
18
int
[] filledIntArray =
new int
[
10
];
19
Arrays.fill(filledIntArray,
7
);
20
displayArray(filledIntArray,
"filledIntArray"
);
21
22
// copy array intArray into array intArrayCopy
23
int
[] intArray = {
1
,
2
,
3
,
4
,
5
,
6
};
24
int
[] intArrayCopy =
new
int
[intArray.length];
25
System.arraycopy(intArray,
0
, intArrayCopy,
0
, intArray.length);
26
displayArray(intArray,
"intArray"
);
27
displayArray(intArrayCopy,
"intArrayCopy")
;
28
29
// compare intArray and intArrayCopy for equality
30
boolean
b = Arrays.equals(intArray, intArrayCopy);
31
System.out.printf(
"%n%nintArray %s intArrayCopy%n"
,
32
(b ?
"=="
:
"!="
));
Fig. 7.22
|
Arrays
class methods and
System.arraycopy
. (Part 1 of 2.)