Overview | Walkthrough | Homework |
ArrayLists - Overview
ArrayList Methods Cheat Sheet
1. Creating an ArrayList
ArrayList<”Type”> list = new ArrayList<”Type”>();
2. Common Methods
Add Elements
list.add(value); → Appends a value to the end.
list.add(index, value); → Inserts value at a specific index.
Access Elements
list.get(index); → Returns the element at the specified index.
Update Elements
list.set(index, value); → Replaces the element at index with value.
Remove Elements
list.remove(index); → Deletes element at index.
list.remove(value); → Deletes the first occurrence of value.
Size of the List
list.size(); → Returns the number of elements.
Check for Elements
list.contains(value); → Returns true if value is in the list.
list.indexOf(value); → Returns the index of the first occurrence of value, or -1 if not found.
ArrayList Loops Cheat Sheet
1. Traversing an ArrayList
You can use for loops or for-each loops to iterate through an ArrayList
.
// Basic for loop
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i)); // Access element at index i
}
2. Using a For-Each Loop
Simplified syntax, no index access.
for (Type item : list) {
System.out.println(item); // Access each element directly
}
3. Modifying Elements
Use a for loop if you need to update values.
for (int i = 0; i < list.size(); i++) {
list.set(i, list.get(i) + 1); // Example: Increment each element
}
4. Avoid ConcurrentModificationException
Cannot modify ArrayList
(add/remove elements) during a for-each loop. Use an iterator or a for loop for such operations.
// Correct usage with a for loop
for (int i = 0; i < list.size(); i++) {
if (list.get(i) < 0) {
list.remove(i);
i--; // Adjust index after removal
}
}
5. Nested Loops with ArrayLists
Use nested loops to compare or process multiple elements.
for (int i = 0; i < list.size(); i++) {
for (int j = i + 1; j < list.size(); j++) {
if (list.get(i).equals(list.get(j))) {
System.out.println("Duplicate: " + list.get(i));
}
}
}