Lecture 17 (Sherriff) - ArrayLists

Lecture Date: Friday, February 20

Arrays are nice… but are honestly a bit of a pain if we want to change the size of the array, or if we want to sort it.

So let’s consider the ArrayList class.

Let’s look at the specific differences between Arrays and ArrayLists:

Array ArrayList Meaning
int[] ArrayList<Integer> type of a list of integer
new int[3] (not doable) create a list that can hold 3 things
(not doable) new ArrayList<Integer>() create an empty list that can grow later
int[] a = {1, 2, 3}; (write a loop) create a list with the given values inside
a[2] = 5 a.set(2, 5) sets the 3rd elements of the list to be value 5
x = a[2] x = a.get(2) retrieves the 3rd element of the list
a.length a.size() the number of elements in the list
(write a loop) a.toString() a pretty textual representation of the list
(not doable) a.add(1110) adds a new element to the end of the list, making the list 1 element longer than it was
(not doable) a.remove(2) removes the element that was at index 2
(not doable) a.remove(new Integer(2)) removes the first 2 from the list (if there is a 2 in the list)
ArrayLists
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Create an ArrayList to hold some names.
ArrayList<String> nameList = new ArrayList<String>();

// Add some names to the ArrayList.
nameList.add("James");
nameList.add("Catherine");
nameList.add("Bill");

// Display the items in nameList and their indices.
for (int index = 0; index < nameList.size(); index++) {
  System.out.println("Index: " + index + " Name: " + nameList.get(index));
}

// Now remove the item at index 1.
nameList.remove(1);

System.out.println("The item at index 1 is removed. " + "Here are the items now.");

// Display the items in nameList and their indices.
for (int index = 0; index < nameList.size(); index++) {
  System.out.println("Index: " + index + " Name: " + nameList.get(index));
}
          

When would we want to use an Array? How about an ArrayList? Why are there two different things to do some of the same stuff?

We will also discuss 2D arrays - although technically they are “arrays of arrays”, and not really 2D. Nor are the 3D if we added another set of square brackets. How does that work when we want to loop through these structures? Can we do this with ArrayLists?

Code from today: