How to avoid java.util.ConcurrentModificationException when iterating through and removing elements from an ArrayList

Two options: Create a list of values you wish to remove, adding to that list within the loop, then call originalList.removeAll(valuesToRemove) at the end Use the remove() method on the iterator itself. Note that this means you can’t use the enhanced for loop. As an example of the second option, removing any strings with a … Read more

Convert list to array in Java [duplicate]

Either: or: Note that this works only for arrays of reference types. For arrays of primitive types, use the traditional way: Update: It is recommended now to use list.toArray(new Foo[0]);, not list.toArray(new Foo[list.size()]);. From JetBrains Intellij Idea inspection: There are two styles to convert a collection to an array: either using a pre-sized array (like … Read more

When to use LinkedList over ArrayList in Java?

Summary ArrayList with ArrayDeque are preferable in many more use-cases than LinkedList. If you’re not sure — just start with ArrayList. TLDR, in ArrayList accessing an element takes constant time [O(1)] and adding an element takes O(n) time [worst case]. In LinkedList adding an element takes O(n) time and accessing also takes O(n) time but LinkedList … Read more