Module 9 · Collections and Generics — topic 2 of 5
Lists and Iterators
ArrayList in depth: adding, inserting, removing, searching and sublists, iterating safely with Iterator and removeIf, ListIterator, and ArrayList versus LinkedList.
Learning objectives
- Use the main List operations correctly
- Remove elements while iterating without ConcurrentModificationException
- Compare ArrayList and LinkedList performance
Definition
A List is an ordered collection that allows duplicates and gives positional access by index. An Iterator is an object that traverses a collection one element at a time and can safely remove the current element.
Introduction
ArrayList is the collection you will use most often. It works like an array that grows automatically, and it adds dozens of useful operations. The one trap to learn early is modifying a list while looping over it.
Why it matters
Lists are the standard way to hold ordered data: rows from a database, items in a cart, lines from a file.
ConcurrentModificationException is one of the first runtime errors every Java developer meets.
Detailed explanation
Adding. add(e) appends; add(i, e) inserts at index i, shifting later elements right; addAll adds a whole collection.
Reading and changing. get(i), set(i, e) (returns the old element), size(), isEmpty(), indexOf(e), lastIndexOf(e) and contains(e) (which use equals).
Removing. remove(int index) removes by position; remove(Object o) removes the first equal element. On a List<Integer>, remove(1) removes index 1 — use remove(Integer.valueOf(1)) to remove the value. clear() empties the list.
Iterating. A for-each loop uses an Iterator behind the scenes. If you change the list's size during the loop (other than through the iterator), the next step throws ConcurrentModificationException. To remove while iterating, call iterator.remove() or, more simply, list.removeIf(condition).
ListIterator can move both ways and set or add elements during iteration. subList(from, to) returns a *view* of part of the list; changes to it affect the original.
ArrayList vs LinkedList. ArrayList: O(1) get and amortised O(1) add at the end, O(n) insert/remove in the middle. LinkedList: O(1) add/remove at the ends or at an iterator's position but O(n) get(i), more memory per element and poor cache behaviour. In practice ArrayList (or ArrayDeque for queues) wins almost always.
Syntax
- Indexes run from 0 to size() - 1.
- remove(int) and remove(Object) are different overloads.
- subList returns a view, not a copy.
Code examples
Everyday list operations
[milk, butter, bread, eggs] size 4 replaced milk: [almond milk, butter, bread, eggs] [almond milk, butter, eggs] contains eggs? true, index of eggs: 2 [10, 30]
Removing while iterating
ConcurrentModificationException! [45, 78, 90] [45, 78, 90]
More examples
ListIterator, subList views and sorting
[Asha, Ravi, Meera, Kiran, John, Priya] [Asha, Meera, Ravi, Kiran, John, Priya] [Kiran, John, Priya] top 3: [95, 95, 82], replaced all: [100, 100, 87, 75, 65]
Step-by-step explanation
listIterator()returns a ListIterator, which can replace the current element withsetand insert after it withaddduring the loop.- Adding through the iterator is allowed, unlike calling
names.addinside a for-each loop. subList(0, 3)is a view of the first three elements; sorting it reorders those positions in the original list.- Clearing the view removes those three elements from the original list.
replaceAllapplies a function to every element; working on a copy leavesscoresunchanged.
Expected output
Running “ListIterator, subList views and sorting” prints exactly:
Practical applications
- Shopping carts, playlists and to-do lists
- Results of database queries mapped to objects
- Filtering out invalid records before processing
Best practices
- Use ArrayList unless you have measured a reason not to.
- Use removeIf, replaceAll and sort instead of manual index loops.
- Be careful with remove on List<Integer>: pass Integer.valueOf for values.
Common mistakes
Modifying a list in a for-each loop
Avoid
Prefer
Structural changes during a for-each loop throw ConcurrentModificationException; removeIf or iterator.remove are safe.
Calling get(i) in a loop on a LinkedList
Avoid
Prefer
Each get(i) on a LinkedList walks from an end, turning the loop into O(n²).
Important notes
Arrays.asListreturns a fixed-size list backed by the array: set works, add and remove throw.- ArrayList's capacity grows by about 50% when full;
new ArrayList<>(expectedSize)avoids repeated growth.
Key takeaways
- List keeps order, allows duplicates and gives index access.
- Remove while iterating with iterator.remove() or removeIf.
- ArrayList is the default; LinkedList is rarely faster.
Try it yourself
- 1Rotate a list right by k positions using subList and addAll.
- 2Merge two sorted ArrayLists into a new sorted list in one pass.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
5 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?
- ModerateWhat is printed?
- ModerateWhat is printed?