Java Reference
In-Depth Information
Self-Test Exercises (continued)
extra code
on website
your class StringSelectionSort . A test program you can use to test your class
follows. (The program is included with the source code provided on the website
that accompanies this topic.)
Import java.util.ArrayList;
public class StringSelectionSortDemo
{
public static void main(String[] args)
{
ArrayList<String> b = new ArrayList<String>();
b.add("time");
b.add("tide");
b.add("clouds");
b.add("rain");
System.out.println("ArrayList values before sorting:");
for (String e : b)
System.out.print(e + " ");
System.out.println();
StringSelectionSort.sort(b);
System.out.println("ArrayList values after sorting:");
for (String e : b)
System.out.print(e + " ");
System.out.println();
}
}
EXAMPLE: Golf Scores
The program in Display 14.3 reads in a list of golf scores and then outputs the
average of the scores and how much each differs from the average. The scores are read
and stored in an ArrayList so that they will be available later in the program to be
output along with how much each differs from the average. This is the kind of thing
that is well suited to being done with an ordinary array. However, it is much easier
and cleaner to use an ArrayList as we did in Display 14.3 .
Our program deals with a list of values of type double . But we use an ArrayList
with base type Double to store these values. We did not use an ArrayList with base
type double because there is no such thing. The base type for an ArrayList must
be a class type (or other reference type). However, thanks to Java's automatic boxing,
we can program as if an object of type ArrayList<Double> can store values of
type double .
The ArrayList automatically keeps track of how many elements are stored in the
ArrayList . If we had used an ordinary partially filled array in our program instead of
an ArrayList , we would need an extra int variable to keep track of how much of the
array is used. When we use an ArrayList , we are spared all the overhead associated
(continued)
 
Search WWH ::




Custom Search