Transcript set10

ArrayLists
Readings: 10.1 (pg. 559 – 571)
1
How would we create a list of strings?

String[] list = new String[10]?

What’s wrong with this?

What if we wanted our list to have more than 10 strings?
2
What’s so great about lists anyway?

Shopping list
Song queue
Student roster
Transaction history
Buddy list
E-mail inbox

And let’s not forget… compiler errors 





3
What operations can we do with lists?





Add items
Remove items
Lookup items
Get list size
…
4
ArrayList

ArrayList is in the java.util package.

Creating a list of strings, syntax:
ArrayList<String> list = new ArrayList<String>();

Creating a list of points, syntax:
ArrayList<Point> list = new ArrayList<Point>();
5
Generic classes

ArrayList<E> represents a family of types, which
includes ArrayList<String> and
ArrayList<Point>

generic class: A class that takes a type parameter
to indicate what kind of values will be used.

Creating a list, general syntax:
ArrayList<E> list = new ArrayList<E>();
("E" is for "Element“)
6
Some ArrayList operations

Adding to a list, general syntax:
list.add(object);
or
list.add(i, object);

// add object at given index
Removing from a list, general syntax:
list.remove(i);
// remove object at given index
7
Example
import java.util.*;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("Alpha");
list.add("Bravo");
list.add("Charlie");
list.add("Delta");
list.add("Echo");
System.out.println(list);
}
}
Output:
[Alpha, Bravo, Charlie, Delta, Echo]
8
Removing items

Before: [Alpha, Bravo, Charlie, Delta, Echo]
list.remove(0);
list.remove(1);

After: [Bravo, Delta, Echo]???

What happened?
9
Exercise

Write a static method named removeRange that
takes an ArrayList and two integers (a start index
and an end index) and that removes all of the
elements whose index is between start, inclusive
and end, exclusive.
10
Solution
public static void removeRange(ArrayList list,
int start, int end) {
for (int i = start; i < end; i++) {
list.remove(start);
}
}
public static void removeRange(ArrayList list,
int start, int end) {
int length = end - start;
for (int i = 1; i <= length; i++) {
list.remove(start);
}
}
11
How are lists implemented?

Arrays underlie ArrayLists.

How do arrays accomplish that?



Shifting elements, constructing new arrays
Does knowing that really matter?
ArrayLists implement a list abstraction.
12
What else can ArrayLists do?
13
Java API Specification
Readings: Appendix C (pg. 857 – 859)
14
Solving bigger problems

Your program needs to do X. What do you do?

Two options:


Write it yourself.
Reuse code.
15