Java Reference
In-Depth Information
EXAMPLE:
(continued)
with partially filled arrays. Those details are taken care of for us automatically. The
code for those details is in the definition of the
ArrayList
class, but there is no need
to look at that code. That code is all implementation detail that we need not worry
about when using an
ArrayList
.
Notice the use of for-each loops in our program. The cleanest and easiest way to
cycle through all the elements in an
ArrayList
is to use a for-each loop.
It is instructive to compare the program in Display 14.3, which uses an
ArrayList
,
with the program in Display 6.4, which does the same thing but uses an ordinary
array. The version that uses an
ArrayList
is much cleaner and even much shorter
than the one that uses an ordinary array. This is because an
ArrayList
does so many
things for you automatically that you would have to explicitly code for if you used
an ordinary array. This is a good example of information hiding and code reuse. The
programmers who defined the
ArrayList
class did a lot of programming for you so
that your programming task is simpler than it would otherwise be.
Display 14.3
Golf Score Program
(part 1 of 3)
1
import
java.util.ArrayList;
2
import
java.util.Scanner;
3
public class
GolfScores
4 {
5
/**
6
Shows differences between each of a list of golf scores and their
average.
7
*/
8
public static void
main(String[] args)
9 {
10 ArrayList<Double> score =
new
ArrayList<Double> ();
11 System.out.println("This program reads golf scores and shows");
12 System.out.println("how much each differs from the average.");
13 System.out.println("Enter golf scores:");
14 fillArrayList(score);
15 showDifference(score);
16 }
17
/**
18
Reads values into the array a.
19
*/
20
public static void
fillArrayList(ArrayList<Double> a)
Parameters of type
ArrayList<Double>()
are handled just like any other class parameter.