Java Reference
In-Depth Information
System.out.println(
"(2) Index is "
+
java.util.Arrays.binarySearch(list,
12
));
char
[] chars = {
'a'
,
'c'
,
'g'
,
'x'
,
'y'
,
'z'
};
System.out.println(
"(3) Index is "
+
java.util.Arrays.binarySearch(chars,
'a'
));
System.out.println(
"(4) Index is "
+
java.util.Arrays.binarySearch(chars,
't'
));
The output of the preceding code is
1. Index is 4
2. Index is -6
3. Index is 0
4. Index is -4
You can use the
equals
method to check whether two arrays are equal. Two arrays are equal
if they have the same contents. In the following code,
list1
and
list2
are equal, but
list2
and
list3
are not.
equals
int
[] list1 = {
2
,
4
,
7
,
10
};
int
[] list2 = {
2
,
4
,
7
,
10
};
int
[] list3 = {
4
,
2
,
7
,
10
};
System.out.println(
java.util.Arrays.equals(list1, list2)
);
// true
System.out.println(
java.util.Arrays.equals(list2, list3)
);
// false
You can use the
fill
method to fill in all or part of the array. For example, the following code
fills
list1
with
5
and fills
8
into elements
list2[1]
and
list2[3-1]
.
fill
int
[] list1 = {
2
,
4
,
7
,
10
};
int
[] list2 = {
2
,
4
,
7
,
10
};
java.util.Arrays.fill(list1,
5
)
;
// Fill 5 to the whole array
;
// Fill 8 to a partial array
java.util.Arrays.fill(list2,
1
,
3
,
8
)
You can also use the
toString
method to return a string that represents all elements in the
array. This is a quick and simple way to display all elements in the array. For example, the fol-
lowing code
toString
int
[] list = {
2
,
4
,
7
,
10
};
System.out.println(Arrays.toString(list));
displays
[2, 4, 7, 10]
.
6.25
✓
✓
What types of array can be sorted using the
java.util.Arrays.sort
method?
Does this
sort
method create a new array?
Check
Point
6.26
To apply
java.util.Arrays.binarySearch(array, key)
, should the array be
sorted in increasing order, in decreasing order, or neither?
6.27
Show the output of the following code:
int
[] list1 = {
2
,
4
,
7
,
10
};
java.util.Arrays.fill(list1,
7
);
System.out.println(java.util.Arrays.toString(list1));
int
[] list2 = {
2
,
4
,
7
,
10
};
System.out.println(java.util.Arrays.toString(list2));
System.out.print(java.util.Arrays.equals(list1, list2));