0

I am having trouble understanding this error. Error message: Exception in thread "main" java.util.ConcurrentModificationException

public static int lift(List<String> list) {
        int index = 0;
        for (String element : list) {
            list.remove(index);
            list.add(index, element.toUpperCase());
            index++;
        }

I'm trying to replace list items but I guess removing and adding in the same iteration is considered a concurrent modification? Is that right? I tried element = element.toUppercase() but that wasn't actually modifying the list at all...

Please help! I am a beginner (obviously)

JeannieM
  • 1
  • 1
  • 1
    The easiest way would be `list.replaceAll(String::toUpperCase);`. – Andy Turner Feb 02 '20 at 19:38
  • 1
    The closest thing to your current code would be to remove the `list.remove` line, and then use `list.set` instead of `list.add`. That would work without ConcurrentModificationException; but it is not efficient for all list types (e.g. LinkedList would be inefficient). – Andy Turner Feb 02 '20 at 19:40
  • 1
    A generally efficient looping way would be: `for (ListIterator it = list.listIterator(); it.hasNext();) { it.set(it.next().toUpperCase()); }` – Andy Turner Feb 02 '20 at 19:47

0 Answers0