Practice: ArrayList

Practice: ArrayList#

Question #1: Which of the following will correctly create an ArrayList that holds double values?

List option1 = new ArrayList<double>();
List<double> option2 = new List<>();
List<Double> option3 = new ArrayList<>();
List<> option4 = new ArrayList<Double>();
ArrayList<Double> option5 = new List<>();

Question #2: Which of the following lines have Boxing or Unboxing?

1    List<Integer> list = new ArrayList<>();
2    list.add(5);
3    int n0 = list.get(0);
4    Integer n1 = list.get(0);
5    Integer num = 11;
6    int n2 = num;
7    int n3 = num.intValue();
8    Integer num2 = Integer.valueOf(11);
9    Integer num3 = num.intValue();
Click to see answer See the table:

line

code

Auto-boxing

Auto-Unboxing

Boxing
(explicit)

Unboxing
(explicit)

2

list.add(5);

✅

3

int n0 = list.get(0);

✅

4

Integer n1 = list.get(0);

5

Integer num = 11;

✅

6

int n2 = num;

✅

7

int n3 = num.intValue();

✅

8

Integer num2 = Integer.valueOf(11);

✅

9

Integer num3 = num.intValue();

✅

✅

Question #3: What is the output of the following code?

 1    ArrayList<String> words = new ArrayList<String>();
 2    words.add("Olympia");
 3    words.add("Everett");
 4    words.add("Tacoma");
 5    words.add("Woodinville");
 6    words.set(1, "Bothell");
 7    words.add(3, "Kenmore");
 8    words.remove(0);
 9    if (!words.contains("Olympia")) {
10        String word = words.get(words.indexOf("Kenmore") + 1);
11        System.out.println(word);
12    } else {
13        System.out.println(words.get(1));
14    }
Click to see answer The output is: `Woodinville`

This is because the list progresses as shown below. After line 8, the list does not contain "Olympia" so it gets the element that is after "Kenmore".

Index

After line 5

After line 7

After line 8

0

Olympia

Olympia

Bothell

1

Everette

Bothell

Tacoma

2

Tacoma

Tacoma

Kenmore

3

Woodinville

Kenmore

Woodinville

4

Woodinville

Question #4: Write a method that will accept an ArrayList<String> and manually remove all occurrences of the argument removeMe. There are several ways to do this. How many can you implement?

See Also: Functional Interface.