Array List
Array List
Array List
Lecture 2
ArrayList
reading: 10.1
2
Naive solution
String[] allWords = new String[1000];
int wordCount = 0;
• Problem: You don't know how many words the file will
have.
– Hard to create an array of the appropriate size.
– Later parts of the problem are more difficult to solve.
5
Lists
• list: a collection storing an ordered sequence of
elements
– each element is accessible by a 0-based index
– a list has a size (number of elements that have been
added)
– elements can be added to the front, back, or elsewhere
– in Java, a list can be represented as an ArrayList object
6
Idea of a list
• Rather than creating an array of boxes, create an
object that represents a "list" of items. (initially an
empty list.)
[]
10
Learning about classes
• The Java API Specification is a huge web page
containing documentation about every Java class and
its methods.
– The link to the API Specs is on the course web site.
11
ArrayList vs. array
• construction
String[] names = new String[5];
ArrayList<String> list = new ArrayList<String>();
• storing a value
names[0] = "Jessica";
list.add("Jessica");
• retrieving a value
String s = names[0];
String s = list.get(0);
12
ArrayList vs. array 2
• doing something to each value that starts with "B"
for (int i = 0; i < names.length; i++) {
if (names[i].startsWith("B")) { ... }
}
for (int i = 0; i < list.size(); i++) {
if (list.get(i).startsWith("B")) { ... }
}
14
Exercise solution
(partial)
ArrayList<String> allWords = new ArrayList<String>();
Scanner input = new Scanner(new File("words.txt"));
while (input.hasNext()) {
String word = input.next();
allWords.add(word);
}
System.out.println(allWords);
15
ArrayList as parameter
public static void name(ArrayList<Type> name) {
• Example:
// Removes all plural words from the given list.
public static void removePlural(ArrayList<String> list) {
for (int i = 0; i < list.size(); i++) {
String str = list.get(i);
if (str.endsWith("s")) {
list.remove(i);
i--;
}
}
}
17
Wrapper classes
Primitive Wrapper
Type Type
int Integer
double Double
char Character
boolean Boolean
• A wrapper is an object whose sole purpose is to hold a primitive
value.
19
Exercise solution
(partial)
ArrayList<Integer> numbers = new ArrayList<Integer>();
Scanner input = new Scanner(new File("numbers.txt"));
while (input.hasNextInt()) {
int n = input.nextInt();
numbers.add(n);
}
System.out.println(numbers);
filterEvens(numbers);
System.out.println(numbers);
...
// Removes all elements with even values from the given list.
public static void filterEvens(ArrayList<Integer> list) {
for (int i = list.size() - 1; i >= 0; i--) {
int n = list.get(i);
if (n % 2 == 0) {
list.remove(i);
}
}
} 20
Other exercises
• Write a method reverse that reverses the order of the
elements in an ArrayList of strings.
21