Chapter 7 ArrayList
Chapter 7 ArrayList
import java.util.ArrayList ;
The size method gives the current size of the array list.
Size is now 3
String name = names.get(2); // Gets the third element of the array list
int i = names.size();
name = names.get(i); // Error
To set an array list element to a new value, use the set method:
names.set(2, "Carolyn");
Declaring and Using Array Lists
An array list has methods for adding and removing elements in the middle.
This statement adds a new element at position 1 and moves all elements
with index 1 or larger by one position.
names.add(1, "Ann")
names.remove(1);
ArrayList<String> names = . . . ;
for (String name : names)
{
System.out.println(name);
}
To make a copy of an array list, construct the copy and pass the original list into
the constructor:
ArrayList<String> newNames = new ArrayList<String>(names);
Working with Array Lists
names.add(1, "Bob"); Inserts an element at index 1. names is now [Ann, Bob, Cindy].
names.remove(0);
Removes the element at index 0. names is now [Bob, Cindy].
names.set(0, "Bill"); Replaces an element with a different value. names is now [Bill, Cindy].
Gets an element.
String name = names.get(i);
ArrayList<Integer>
squares = new
ArrayList<Integer>(); for
(int i = 0; i < 10; i++)
{
squares.add(i * i); Constructs an array list holding the first ten
}
squares.
Wrapper Classes
You cannot directly insert primitive type values into array lists.
Like truffles that must be in a wrapper to be sold, a number must be placed in
a wrapper to be stored in an array list.
Concrete example
Recommendations
If the size of a collection never
changes, use an array.
If you collect a long sequence of primitive type values and you are concerned about efficiency,
use an array.
Otherwise, use an array list.
Choosing Between Array Lists and Arrays
section_7/LargestInArrayList.java
1 import java.util.ArrayList;
2 import java.util.Scanner;
3
4 /**
5 This program reads a sequence of values and prints them, marking the largest
value.
6 */
7 public class LargestInArrayList
8 {
9 public static void main(String[] args)
10 {
11 ArrayList<Double> values = new ArrayList<Double>();
12 // Read
13 inputs
14 System.out.println("Please enter values, Q to quit:");
15 Scanner in = new Scanner(System.in);
16 while (in.hasNextDouble())
17 {
18 values.add(in.nextDouble());
19 }
20
21 // Find the largest
22 value
23 double largest = values.get(0);
24 for (int i = 1; i < values.size(); i++)
25 {
26 if (values.get(i) > largest)
27 {
28 largest = values.get(i);
29 }
30 }
31
32 // Print all values, marking the
33 largest
34
Program
35 Run:
for (double element : values)
Answer:
ArrayList<Integer> primes = new ArrayList<Integer>(); primes.add(2);
primes.add(3);
primes.add(5);
primes.add(7);
primes.add(11);
Self Check 7.36
Given the array list primes declared in Self Check 35, write a loop to print its elements in reverse order,
starting with the last element.
Answer:
for (int i = primes.size() - 1; i >= 0; i--)
{
System.out.println(primes.get(i));
}
Self Check 7.37
What does the array list names contain after the following statements?
ArrayList<String> names = new ArrayList<String>; names.add("Bob");
names.add(0, "Ann");
names.remove(1);
names.add("Cal");
What are the contents of names1 and names2 after these statements?
ArrayList<String> names1 = new ArrayList<String>();
names1.add("Emily");
names1.add("Bob");
names1.add("Cindy");
ArrayList<String> names2 = new ArrayList<String>();
names2.add("Dave");
append(names1, names2);
1 import java.util.Scanner;
2
3 public class ScoreTester
4 {
5 public static void main(String[] args)
6 {
7 Scanner in = new Scanner(System.in);
8 double expected = in.nextDouble();
9 Student fred = new Student(100);
10 while (in.hasNextDouble())
11 {
12 if (!fred.addScore(in.nextDouble()))
13 {
14 System.out.println("Too many scores.");
15 return;
16 }
17 }
18 System.out.println("Final score: " + fred.finalScore());
19 System.out.println("Expected: " + expected);
20 }
21 }
Input and Output Redirection
Section_8/input1.txt
30
10
20
5
Program Run:
Final score: 30
Expected: 30
Output redirection:
java ScoreTester < input1.txt > output1.txt
Self Check 7.42
Suppose you modified the code for a method. Why do you want to repeat tests that already passed with
the previous version of the code?
Answer: Add a test case to the test suite that verifies that the error is fixed.
Self Check 7.44
Why doesn't the ScoreTester program contain prompts for the inputs?
Answer: There is no human user who would see the prompts because input
is provided from a file.