Java Reference
In-Depth Information
/**
Swap
b[i]
and
b[j] */
public static void
swap(
int
[] b,
int
i,
int
j) {
int
temp= b[i];
b[i]= b[j];
b[j]= temp;
}
This fact will be quite useful for writing code for sorting arrays.
8.1.7
Initializing class-type arrays
Be careful when creating an array whose base type is some class type, for the
array element themselves are initially
null
. Consider the following statement:
String d=
new
String[4];
After execution, each element of
d
automatically contains
null
, as shown to the
left in Fig. 8.1.
String
objects must be explicitly created; for example, after the
assignment
d[2]= "xyz";
, the array is as shown in the right diagram of Fig. 8.1.
8.2
Talking about array segments
In every scientific field, notation is developed to concisely and clearly discuss
concepts of that field. It will help us to take some time to do the same for talk-
ing about arrays.
8.2.1
Range notation:
h..k
We have already introduced the notation
4..7
to stand for the range of integers
4
,
5
,
6
, and
7
. In general, we can use integer expressions instead of constants.
Here are two examples:
h..k
stands for the collection of integers
h
,
h+1
,
h+2
,
…
,
k-1
,
k
.
The range of an array
b
is
0..b.length - 1
.
By convention, the range
h..h - 1
stands for an empty collection of integers.
Thus:
a0
null
null
null
null
a1
a0
d a0
d a0
null
null
a1
null
String
"xyz"
Figure 8.1:
Initializing array elements
Search WWH ::
Custom Search