Java Reference
In-Depth Information
[0]
[1]
[2]
[3]
[4]
list
31
33
35
37
39
Suppose that we want to report the first, middle, and last values in the list. From
an examination of the preceding diagram, we can see that these values occur at
indexes 0, 2, and 4, which means we could write the following code:
// works only for an array of length 5
System.out.println("first = " + list[0]);
System.out.println("middle = " + list[2]);
System.out.println("last = " + list[4]);
This technique works when the array is of length 5, but suppose that we change
the length of the array? If the array has a length of 10, for example, this code will
report the wrong values. We need to modify it to incorporate
list.length
, just as
we modified the standard traversing loop.
The first element of the array will always be at index 0, so the first line of code
doesn't need to change. You might at first think that we could fix the third line of
code by replacing the
4
with
list.length
:
// doesn't work
System.out.println("last = " + list[list.length]);
However, this code doesn't work. The culprit is zero-based indexing. In our example,
the last value is stored at index 4, not index 5, when
list.length
is 5. More generally,
the last value will be at index
list.length - 1
. We can use this expression directly in
our
println
statement:
// this one works
System.out.println("last = " + list[list.length - 1]);
Notice that what appears inside the square brackets is an integer expression (the
result of subtracting 1 from
list.length
).
A simple approach to finding the middle value is to divide the length of the list
in half:
// is this right?
System.out.println("middle = " + list[list.length / 2]);
When
list.length
is 5, this expression evaluates to
2
, which prints the correct
value. But what about when
list.length
is 10? In that case the expression evalu-
ates to
5
, and we would print
list[5]
. But when the list has an even length, there
are actually two values in the middle. For a list of length 10, the two values are at
list[4]
and
list[5]
. In general, the preceding expression always returns the second
of the two values in the middle when the list is of even length.
Search WWH ::
Custom Search