Java Reference
In-Depth Information
Exercise 4.68 What is wrong with the following array creation? Correct it.
double[] prices = new double(50);
4.16.4
Using array objects
The individual elements of an array are accessed by indexing the array. An index is an integer
expression written between square brackets following the name of an array variable. For in-
stance:
labels[6]
machines[0]
people[x + 10 - y]
The valid values for an index expression depend upon the length of the array on which they
are used. As with other collections, array indices always start at zero and go up to one less than
the length of the array. So the valid indices for the hourCounts array are 0 to 23, inclusive.
Pitfall Two very common errors are to think that the valid indices of an array start at 1, and to use
the value of the length of the array as an index. Using indices outside the bounds of an array will
lead to a runtime error called an ArrayIndexOutOfBoundsException .
Expressions that select an element from an array can be used anywhere that a variable of the
base type of the array could be used. This means that we can use them on both sides of assign-
ments, for instance. Here are some examples that use array expressions in different places:
labels[5] = "Quit";
double half = readings[0] / 2;
System.out.println(people[3].getName());
machines[0] = new TicketMachine(500);
Using an array index on the left-hand side of an assignment is the array equivalent of a mutator
(or set method), because the contents of the array will be changed. Using one anywhere else
represents the equivalent of an accessor (or get method).
4.16.5
Analyzing the log file
The hourCounts array created in the constructor of LogAnalyzer is used to store an analysis
of the access data. The data is stored into it in the analyzeHourlyData method and displayed
from it in the printHourlyCounts method. As the task of the analyze method is to count
how many accesses were made during each hour period, the array needs 24 locations—one for
each hour period in a 24-hour day. The analyzer delegates the task of reading its log file to a
LogfileReader .
The LogfileReader class is quite complex, and we suggest that you do not spend too much
time investigating its implementation. Its role is to handle the task of breaking up each log line
 
Search WWH ::




Custom Search