Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 134 ยท Collections

Mutable Collections and Iterators

Learn Kotlin mutable collections: add, remove, removeAll, retainAll, removeIf, ListIterator, ArrayDeque, read-only views versus copies, and how to avoid ConcurrentModificationException.

So far most collections in this section were read-only: you create them with listOf, and transformation functions hand you new ones. Real programs also need collections that change: a shopping cart that gains and loses items, a queue of jobs, a cache that grows. For those, Kotlin has the mutable types: MutableList, MutableSet, MutableMap and the double-ended ArrayDeque.

This lesson shows how to add, replace and remove elements, why removing items inside a for loop crashes with the dreaded ConcurrentModificationException, and the three safe ways to do it. You also meet iterators, learn what "read-only" really means (it is a compile-time promise, not a runtime guarantee), and see the difference between a view and a copy. You should know the basics from Collections Overview and Lists.

Changing a mutable list

Kotlin Adding, setting and removing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is [99, 1, 2, 3, 4, 5, 6, 7], then 99, [-1, 100, 2, 3, 4, 5, 6, 7], -1, true, false, [2, 3, 4, 5, 6, 7], [2, 3, 4, 5], [2, 3, 4], [2, 8, 9, 3, 4] and true. Take them in turn:

  • add(x) appends; add(index, x) inserts and shifts later elements to the right. addAll adds many, and += is a shortcut for add/addAll on a val that holds a mutable list.
  • list[1] = 100 replaces an element. set(index, x) does the same but returns the old value, which is why 99 was printed.
  • removeAt(index) removes by position and returns the removed element (-1 here). remove(element) removes the first equal element and returns whether it found one: true for 100, false for 1234.
  • removeAll { condition } removes every matching element; retainAll(collection) keeps only elements that are in the other collection.
  • clear() empties the list.

ArrayList is the class behind mutableListOf(), and you can create one directly with three constructors: ArrayList<String>() for an empty list, ArrayList<Int>(100) to reserve room for about 100 elements (a performance hint, not a size limit), and ArrayList(otherCollection) to copy another collection:

Kotlin ArrayList constructors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is [x], [1] and [a, b, c, d]. The copy is independent: changing it never changes the list it was built from.

Notice that inserting or removing near the front of an ArrayList shifts every element after it, which costs O(n). Appending at the end is O(1) on average.

remove(element) versus removeAt(index)

Java has a notorious trap: for a List<Integer>, remove(2) means "remove the element at index 2". Kotlin fixes this by giving the two operations different names. See what that means for a list of Int:

Kotlin remove versus removeAt

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first call prints false and leaves [10, 20, 30, 40] unchanged: remove(2) looked for the value 2, and there is none. removeAt(2) removes the element at position 2, printing 30 and leaving [10, 20, 40]. For a set, add returns true only if the element was new (false for the duplicate 2, true for 9), and remove(1) returns true, leaving [2, 3, 9].

Use the return values. add on a set, remove on any collection and put on a map all tell you whether something changed or what the old value was, so you rarely need a separate contains check first.

The classic crash: removing while iterating

Here is the bug nearly every Kotlin and Java beginner writes at least once. We want to remove an element during a for loop:

Kotlin Removing inside a for loop (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The program dies with Exception in thread "main" java.util.ConcurrentModificationException. A for loop over a collection uses an iterator behind the scenes. The list counts how many times it has been structurally modified (elements added or removed), and the iterator remembers the count from when it started. When the loop asks for the next element and the counts disagree, it fails fast with this exception rather than continue with confusing data. The name suggests threads, but it happens in single-threaded code too.

There is a famous quirk: remove the second-to-last element and the loop ends quietly, because the iterator's hasNext() is already false by then. That makes the bug appear to work in some tests and crash in others, which is worse than a consistent crash. Never rely on it.

Safe ways to remove

Kotlin Safe removal while processing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The results are [a, c, d], [a, d], [1, 3, 5], [2, 4], [3, 4] and [x, z]. In order of preference:

  1. removeAll { } or removeIf { } remove every matching element in one call. This is the best choice: short, clear and fast (one pass instead of repeated shifting). removeIf comes from Java; removeAll { } is the Kotlin version.
  2. Build a new collection with filter (or filterNot) instead of mutating. If you do not need to change the original in place, this is the safest and often the clearest option.
  3. Use the iterator's own remove(). The iterator knows about its own removal, so it keeps the modification count in sync. Call next() first, then remove() removes that last returned element.
  4. Iterate over a copy (for (x in copy.toList())) when you want a loop body with complex logic. The loop walks the snapshot while you edit the original.
  5. Loop by index from the back. Removing at position i shifts only later elements, which you have already visited.

Do not forget the opposite mistake of removing forward by index: for (i in list.indices) if (...) list.removeAt(i) skips elements and eventually throws IndexOutOfBoundsException, because the list shrinks while the range stays fixed.

Iterators and ListIterator

Iterator has hasNext() and next(). A MutableIterator adds remove(). A ListIterator also moves backwards and knows the index, and its mutable form can set and add while walking:

Kotlin ListIterator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You see first is ann, then [ann, BOB, bobby, di], then di bobby BOB ann , then 3 and [di, bobby, BOB, ann]. The walk replaced bob by BOB, inserted bobby right after it, and removed cy, all without a ConcurrentModificationException, because every change went through the iterator. listIterator(n) starts at position n, and previousIndex() there is n - 1. asReversed() is a cheap reversed view.

Use a ListIterator when you must edit during one pass. For simple cases map, filter or removeAll are easier.

Read-only is not immutable

Kotlin's List interface has no add method, so you cannot change a List through that reference. But that is a compile-time rule only. Two things follow:

Kotlin Views, copies and casts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is [1, 2, 3, 4], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5], true and true.

  • view is the same object typed as read-only. It sees every later change to original. If you return original from a function declared to return List<Int>, callers cannot call add on it, but they see your updates and could cast it back.
  • toList() creates an independent copy (a snapshot). toMutableList() makes a copy you can edit without touching the source.
  • The last line is a surprise: listOf(1, 2) is MutableList<*> is true on the JVM, because the object behind listOf is a Java list class that implements MutableList. The compiler hides the methods; the runtime does not forbid the cast. Let us see what happens if someone tries:
Kotlin Casting away read-only (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The program stops with Exception in thread "main" java.lang.UnsupportedOperationException. The list you get from listOf really refuses changes at run time, but that is a JVM implementation detail. Do not write code that depends on it, and never cast a read-only collection to a mutable one. If a caller needs a modifiable list, give it a copy.

And of course, without a cast the compiler stops you earlier:

Kotlin add on a read-only list (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The error is main.kt:3:10: error: unresolved reference 'add' on receiver of type 'List<Int>'. The fix is mutableListOf(1, 2, 3), or val bigger = list + 4 to get a new list.

A related beginner confusion: val versus mutable. val list = mutableListOf(1) means the variable always points to the same list, but the list can change. var list = listOf(1) can be reassigned to a different list (list += 2 creates a new list each time), but no list object ever changes. Prefer val with a read-only type, and use a mutable collection only inside the function or class that owns it.

Mutating maps and sets, and their views

Maps and sets follow the same patterns. A mutable map's keys, values and entries are live views: removing from them removes from the map.

Kotlin Mutable maps and sets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is {a=1, c=3}, {a=1}, {}, {2=y}, {2=Y} and [1, 8]. The three first lines remove through entries, values and keys respectively, each time changing the underlying map. replaceAll rewrites every value in place. The ConcurrentModificationException applies to maps and sets as well: adding a key to a map while looping over its keys fails on the next step. Use toMap() or iterate over keys.toList() for a snapshot.

ArrayDeque: a double-ended queue

If you add and remove at both ends, ArrayDeque (from the Kotlin standard library) is the right tool. Unlike a plain list, removing the first element is O(1), so it works well as a queue (first in, first out) and as a stack (last in, first out).

Kotlin ArrayDeque as queue and stack

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is [0, 1, 2], 0, 2, [1], b, null, [1, 4, 5] and [0, 0, 0]. removeFirst() and removeLast() throw NoSuchElementException on an empty deque; the OrNull forms return null. Because ArrayDeque is a MutableList, you can also index it and use all list functions. The subList(1, 3).clear() trick deletes a whole range from the parent list in one operation, since the sublist is a live view.

Be careful with MutableList.removeFirst() and removeLast() on plain lists: newer JDKs added members with the same names to List, so on old Android runtimes the same source can behave differently. If your code must run on older platforms, use removeAt(0), removeAt(lastIndex) or an ArrayDeque.

Pitfalls

  • Modifying a collection inside a for loop over itself throws ConcurrentModificationException, or, worse, sometimes does not.
  • remove(x) is by value, removeAt(i) by index. Do not mix them up with lists of numbers.
  • Returning your internal MutableList as List leaks a live view. Return toList() when callers must see a snapshot.
  • Casting a read-only list to a mutable one compiles and fails at run time.
  • Sharing mutable collections across threads needs synchronisation or a concurrent collection; see Threads and Java Concurrency.
  • Quadratic removal. Calling remove(x) for thousands of elements in a loop is O(nยฒ). Collect what to keep with filter, or call removeAll once.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does mutableListOf(10, 20, 30, 40).remove(2) do?

    remove(element) works by value and returns false when absent. To remove by position, use removeAt(2).
  2. 2. Why does removing items inside for (x in list) often throw ConcurrentModificationException?

    The iterator compares the list's modification count with the one it saw when it started and fails fast if they differ.
  3. 3. Which is the cleanest way to delete all negative numbers from a MutableList<Int> named nums?

    removeAll { } removes every match in a single pass. The loops either crash or skip elements.
  4. 4. What is true about val view: List<Int> = mutableList?

    Read-only is a compile-time view over the same object. Use toList() for a real snapshot.
  5. 5. Which collection is best for removing from the front of a queue in O(1)?

    ArrayDeque removes from both ends in constant time, while removeAt(0) on an ArrayList shifts all remaining elements.

Summary

  • Mutable collections (MutableList, MutableSet, MutableMap, ArrayDeque) offer add, addAll, set, remove, removeAt, removeAll, retainAll and clear.
  • remove(element) is by value and removeAt(index) by position; return values tell you what changed.
  • Never remove from a collection inside a for loop over it: use removeAll { }, filter, the iterator's remove(), a copy, or a backwards index loop.
  • ListIterator can walk both ways and set, add and remove safely.
  • List is read-only, not immutable: it can be a live view of a mutable list, and the JVM cast as MutableList compiles but throws UnsupportedOperationException here. Use toList() and toMutableList() to copy.
  • ArrayDeque is the right tool for queues and stacks.

Next: Sequences