Lecture 11 (Edwards) - ArrayLists and 2D Arrays

Lecture Date: Wednesday, February 18

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));
}
          

We will also discuss 2D Arrays and how they are really arrays of arrays.

Code: