Java Reference
In-Depth Information
into separate data values, but we can abstract from the implementation details by considering
just the headers of two of its methods:
public boolean hasNext()
public LogEntry next()
These exactly match the methods we have seen with the Iterator type, and a LogfileReader
can be used in exactly the same way, except that we do not permit the remove method to be used.
The hasNext method tells the analyzer whether there is at least one more entry in the log file, and
the next method then returns a LogEntry object containing the values from the next log line.
From each LogEntry , the analyzeHourlyData method of the analyzer obtains the value of
the hour field:
int hour = entry.getHour();
We know that the value stored in the local variable hour will always be in the range 0 to 23,
which exactly matches the valid range of indices for the hourCounts array. Each location in
the array is used to represent an access count for the corresponding hour. So each time an hour
value is read, we wish to update the count for that hour by 1. We have written this as
hourCounts[hour]++;
Note that it is the value stored in the array element that is being incremented and not the hour
variable. The following alternatives are both equivalent, as we can use an array element in ex-
actly the same way as we would an ordinary variable:
hourCounts[hour] = hourCounts[hour] + 1;
hourCounts[hour] += 1;
By the end of the analyzeHourlyData method, we have a complete set of cumulative counts
for each hour of the log period.
In the next section, we look at the printHourlyCounts method, as it introduces a new control
structure that is well suited to iterating over an array.
4.16.6
The for loop
Java defines two variations of for loops, both of which are indicated by the keyword for in
source code. In Section 4.9, we introduced the first variant, the for-each loop , as a convenient
means to iterate over a flexible-size collection. The second variant, the for loop , is an alterna-
tive iterative control structure 5 that is particularly appropriate when:
we wish to execute a set of statements a fixed number of times
we need a variable inside the loop whose value changes by a fixed amount—typically in-
creasing by 1—on each iteration
5 Sometimes, if people want to make clearer the distinction between the for loop and the for-each loop,
they also talk about the former as the “old-style for loop,” because it has been in the Java language
longer than the for-each loop. The for-each loop is sometimes referred to as the “enhanced for loop.”
 
Search WWH ::




Custom Search