lecture18 (1)
lecture18 (1)
Introduction to ArrayLists
Problem with Arrays
Consider the following problem: Read words from a text
file and
store the data in memory.
String[] allWords = new String[2500];
Problem: You don't know how many words the text file
contains.
4
A list is a collection that stores an ordered sequence of elements. Each element in
the list can be accessed and manipulated using its position, which is determined by a
0-based index (i.e., the first element is at index 0, the second at index 1, and so on).
ordered Sequence:
The elements in a list maintain the order in which they were added. This order is
preserved unless explicitly changed (e.g., by sorting or modifying the list).
Index-Based Access:
Each element is accessible by its index. For example:
list.get(0); // Retrieves the first element
Dynamic Size:
A list has a size that represents the number of elements it contains. Unlike arrays, the
size of a list can dynamically grow or shrink as elements are added or removed.
Insertion Flexibility:
Elements can be added:
To the front (index 0)
To the back (end of the list)
5
To a specific position (any valid index)
Idea of a list
• Rather than creating an array of boxes, create an
object that represents a "list" of items. (initially an
empty list.)
[]
• You can add items to the list.
– The default behavior is to add to the end of the list.
[hello, ABC, goodbye, okay]
7
What the list tracks for you:
The list automatically keeps track of:
The values of the items (e.g., "hello", "ABC").
The order of the items (they remain in the order you added them).
The index of each item (e.g., "hello" is at index 0, "ABC" is at index
1, and so on).
The total size of the list (how many items it contains).
8
Think of an "array list" as a smart, flexible array that
automatically grows as needed and keeps track of the
items, their order, and how many items there are. You
just add items and let it handle the details for you!
9
Type Parameters
(Generics)
ArrayList<Type> name = new ArrayList<Type>();
12
boolean add(E obj)
Description: Adds an element to the end of the list. Returns true if successful.
import java.util.ArrayList;
13
E get(int index)
Description: Returns the element at the specified index.
E remove(int index)
Description: Removes and returns the element at the specified index, shifting elements to the
left.
// Remove the element at index 0
int removed = list.remove(0); // Removes the element at index 0
System.out.println("Removed value: " + removed); // Output: 5
System.out.println("After remove: " + list); // Output: [10, 20]
7. int size()
Description: Returns the number of elements in the list.
// Get the size of the list
int size = list.size();
System.out.println("Size of the list: " + size); // Output: 1
toString()
Description: Returns a string representation of the list.
// Print the list as a string
System.out.println("List as a string: " + list); // Output: [30]
}
}
15
After add: [10, 20]
After add at index: [5, 10, 20]
Value at index 1: 10
Removed value: 5
After remove: [10, 20]
After remove by value: [20]
Replaced value: 20
After set: [30]
Size of the list: 1
List as a string: [30]
16
17
18
import java.util.ArrayList;
19
import java.util.ArrayList;
20
import java.util.ArrayList;
21
import java.util.ArrayList;
22
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);
23
Construction
Explanation:
24
Storing a Value
Retrieving a Value
list.add(“Michael”);
list.add(“Jessica”);
list.add(“Lee”); //{“Michael”, “Jessica”, “Lee”}
list.add(1,“Sarah”);//{“Michael”, “Sarah”,”Jessica”, “Lee”}
String store=list.set(2,”Mary”)
//{Michael,Sarah,Mary,Lee}, store=“Jessica”
String store2=list.get(3);//store2=“Lee”
String store3=list.remove(1);
//{Michael,Mary,Lee}, store3=“Sarah”
Key Points to Remember:
add(): Appends to the end or inserts at a specific index (shifting elements to the
right).
set(): Replaces an element at a specific index and returns the old value.
get(): Retrieves the element at a specific index.
remove(): Removes the element at a specific index, returns it, and shifts subsequent
elements to the left. 26
Traversing an Arraylist
It is common to use for loops to access arraylist elements. This is
called
traversing the arraylist.
27
28
29
Traversing an Arraylist
We can use a for each loop traverse the arraylist. The list arrayList
below is
an arrayList of Strings from the previous slides.
Note this syntax is the same for both arrays and arraylists!
Do not use the enhanced for each loop if you want to add or remove
elements when traversing a list because it will throw
a ConcurrentModificationException error. Since for each loops
do not use
an index, you cannot do this special case of incrementing only if it is
changed.
So if you are going to add or remove items or you need the index, 30
Common Error:Remove
Items
Removing an element from an arraylist requires care as elements
are shifted
left.
}
}
This is an error! Once a word is removed, words are shifted to the
left, this will cause the next word to be skipped!
31
Remove Words
One way to fix the previous error is add a i-- correction.
32
Remove Words
Or alternatively, we can traverse the array backwards; this
eliminates the
need to do i--. Do you see why the following works?
33
ArrayList as parameter
A method can accept an arraylist as a parameter.
public static void name(ArrayList<Type> name) {
Write a method that count all of the letters in all of the Strings from
an
ArrayList of Strings.
34
ArrayList as parameter
35
Returns an ArrayList
You can also return a list:
public static ArrayList<Type> methodName(params)
37
ArrayList of Integers
int total = 0;
for (int i = 0; i < myList.size(); i++){
total += myList.get(i);
}
System.out.println(total);
Output: 100
38
ArrayList "mystery"
ArrayList<Integer> list = new ArrayList<Integer>();
39
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.
inde 0 1 2 3
x
valu Mart Kevi Vic Larr
e y n ki y 40
ArrayList "mystery" 2
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= 5; i++) {
list.add(2 * i); // [2, 4, 6, 8, 10]
}
41
ArrayList "mystery" 3
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= 5; i++) {
list.add(2 * i); // [2, 4, 6, 8, 10]
}
Answer:
[42, 42, 42, 42, 42, 2, 4, 6, 8, 10]
42
Objects storing
collections
• An object can have an array, list, or other collection as
a field.
public Course() {
students = new ArrayList<Student>();
...
}
43
Lab 1
Write the following static methods.
45
Lab 3(Processing)
Tank Shooting Lab: Download the template for this processing
lab on my website.
46