Lists are built into Java. There are several variations of them. We will use the LinkedList class in this course. These are a generic type of lists, so to create a variable containing a list, you need to supply the type of the data in the list. For example, the following statements defines an empty linked list of integers.
LinkedListL = new LinkedList ();
One key difference between Java lists and Racket lists is that adding elements to a list modifies the original list in Java. The analogous operator to cons in Java is called addFirst. The following expression adds 5 to the list L:
L.addFirst(5);However, in Java, L now contains the number 5. The original list L is no longer available. (Contrast this to Racket, in which (cons 5 L) would leave L unchanged.)
Here is the method to sum up a list of integers:
int sum (LinkedList<Integer> numList) {
int result;
result = 0;
for ( Integer n : numList ) {
result = result + n;
}
return result;
}
To understand the structure of this code, it helps to step back and see the pieces of the construct. In the following code skeleton, substitute single expressions for terms in all-caps, and substitute computations for descriptions in square-brackets:
RETURN-TYPE result; // a local variable (field) in the class
result = [the result when the list is empty]
for ( TYPE VARNAME : SPECIFIC-LIST ) {
result = [expression to build new result from current
value of result and VARNAME];
}
return result;
For those who took CS1101, this is just the accumulator-style programs
that you did in the last segment of that course.
Study this pattern and try it out on the following examples. The examples are for a list of Songs, where a song has an artist, title, and price (feel free to use an int for the price).
Write a method numCheap that consumes a
LinkedList and produces an integer indicating
how many songs cost less than two dollars.
Write a method discount that consumes a
LinkedList and produces
a LinkedList in which each song is discounted
by 10%. Do this without modifying the individual songs.
Repeat the previous problem, this time changing the price in the song classes in the original list.
Write a method discography that consumes
a LinkedList and an artist (String) and produces
a LinkedList with all songs by that artist.
Feel free to see us in office hours or ask on the board if you have questions on any of these.