Array Lists
Array Lists
2
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
3
Idea of ArrayList<>
• ArrayList<E> where E indicates the type of items that will be
included in the ArrayList, is a class that lets you collect objects
just like an array does; but it has two significant conveniences:
− ArrayList can grow and shrink as needed (it is initially an empty list).
− ArrayList class supplies methods for many common tasks, such as
inserting and removing elements
• The default behavior is to add to the end of the list.
• ArrayList keeps track of the element values that have been added
to it, their order, indexes, and its total size.
– Think of an "array list" as an automatically resizing array object.
– Internally, the list is implemented using an array and a size field.
4
Type Parameters (Generics)
ArrayList<Type> name = new ArrayList<Type>();
• When constructing an ArrayList, you must specify the
type of elements it will contain between < and >.
– This is called a type parameter or a generic class.
• Example
ArrayList<String> names = new ArrayList<String>();
names.add("Marty Stepp");
names.add("Stuart Reges");
• When you construct an array list, it has a size 0
− The size increases every time an element is added to the array list
− The size method yields number of elements
5
ArrayList methods (10.1)
add(value) appends value at end of list
add(index, value) inserts given value just before the given index, shifting
subsequent values to the right
clear() removes all elements of the list
indexOf(value) returns first index where given value is found in list (-1 if not
found)
get(index) returns the value at given index
remove(index) removes/returns value at given index, shifting subsequent
values to the left
set(index, value) replaces value at given index with given value
size() returns the number of elements in list
toString() returns a string representation of the list
such as "[3, 42, -7, 15]"
contains(value) returns true if given value is found somewhere in this list
lastIndexOf(value) returns last index value is found in list (-1 if not found)
6
add and set methods
ArrayList<String> names = new ArrayList<String>();
System.out.println("Names = " + names);
names.add("Marty Stepp");
System.out.println(“Names = " + names);
names.add("Stuart Reges");
System.out.println("Names = " + names);
names.add(0, "Hello");
System.out.println("Names = " + names);
names.add(2, "and");
System.out.println("Names = " + names);
names.set(2, "or");
System.out.println("Names = " + names);
Output
• Names = []
• Names = [Marty Stepp]
• Names = [Marty Stepp, Stuart Reges]
• Names = [Hello, Marty Stepp, Stuart Reges]
• Names = [Hello, Marty Stepp, and, Stuart Reges]
• Names = [Hello, Marty Stepp, or, Stuart Reges] 7
get and remove methods
− Removing moves all elements after the removed element down by one position,
and reduces the size of the array list by 1
Output
Names = [Hello, Marty Stepp, or, Stuart Reges]
Or
Stuart Reges
Names = [Hello, Marty Stepp, Stuart Reges]
8
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);
Output
List = [Maria, Derek, Erica, Livia, Jack, Anita, Kendal, Jamie]
10
ArrayList as parameter
public static void name(ArrayList<Type> name) {
• Example:
//search for a string target and replace it with replacement
public static void replace (ArrayList<String> list,
String target, String replacement){
int index = list.indexOf(target);
if (index>=0){
list.set(index, replacement)
}
}
11
ArrayList of primitives?
• The type you specify when creating an ArrayList must be an
object type; it cannot be a primitive type.
– You cannot insert primitive types directly into array lists
// illegal -- int cannot be a type parameter
ArrayList<int> list = new ArrayList<int>();
12
Wrappers
14
Out-of-bounds
• Legal indexes are between 0 and the list's size() - 1.
– Reading or writing any index outside this range will cause an
IndexOutOfBoundsException.
index 0 1 2 3
17
Complete Example
// Withdraws the given amount of money from the user's account.
// If the user does not have enough money, or if the amount of money is negative, the
// method does nothing. Also records a log entry of the withdrawal to be printed later.
public void withdraw(double money) {
if (0 <= money && money <= balance) {
balance = balance - money;
transactions.add("Withdrawal of $" + money);
}
}
// Returns the account user's current balance.
public double getBalance() {
return balance;
}
// Returns the account user's ID number.
public double getID() {
return id;
} 18
Complete Example
// Prints a log of all transactions (deposits and withdrawals) that have
// been made on this account, one per line.
public void printLog() {
for (int i = 0; i < transactions.size(); i++) {
String element = transactions.get(i);
System.out.println(element);
}
}
}
19
Complete Example -Test Program
// This 'client' program uses a BankAccount object and calls
// the printLog method we wrote in class.
public class UseAccount {
public static void main(String[] args) {
BankAccount marty = new BankAccount(19);
marty.deposit(7.84);
marty.withdraw(2.53);
marty.deposit(6.19);
marty.deposit(2.58);
marty.withdraw(999.99); // should fail (no transaction log)
marty.printLog();
System.out.println();
marty.withdraw(4.18);
marty.deposit(-123.45); // should fail (no transaction log)
marty.printLog();
}
20
}