Java Reference
In-Depth Information
Random Access
Manipulating values in any order whatsoever to allow quick access to each
value.
An array can provide random access because it is allocated as a contiguous block
of memory. The computer can quickly compute exactly where a particular value will
be stored, because it knows how much space each element takes up in memory and it
knows that all the elements are allocated right next to one another in the array.
When you work with arrays, you can jump around in the array without worrying
about how much time it will take. For example, suppose that you have constructed an
array of temperature readings that has 10,000 elements and you find yourself wanting
to print a particular subset of the readings with code like the following:
System.out.println("#1394 = " + temps[1394]);
System.out.println("#6793 = " + temps[6793]);
System.out.println("#72 = " + temps[72]);
This code will execute quickly even though you are asking for array elements that
are far apart from one another. Notice also that you don't have to ask for them in
order. You can jump to element 1394, then jump ahead to element 6793, and then
jump back to element 72. You can access elements in an array in any order that you
like, and you will get fast access.
Later in the chapter we will explore several algorithms that would be difficult to
implement without fast random access.
Common Programming Error
Off-by-One Bug
When you converted the Temperature1 program to one that uses an array, you
modified the for loop to start with an index of 0 instead of 1. The original for
loop was written the following way:
for (int i = 1; i <= numDays; i++) {
System.out.print("Day " + i + "'s high temp: ");
int next = console.nextInt();
sum += next;
}
Because you were storing the values into an array rather than reading them
into a variable called next , you replaced next with temps[i] :
// wrong loop bounds
for (int i = 1; i <= numDays; i++) {
Continued on next page
 
Search WWH ::




Custom Search