How to avoid “ConcurrentModificationException” while removing elements from `ArrayList` while iterating it? [duplicate]
How to avoid “ConcurrentModificationException” while removing elements from `ArrayList` while iterating it? [duplicate]
How to avoid “ConcurrentModificationException” while removing elements from `ArrayList` while iterating it? [duplicate]
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
Either: Foo[] array = list.toArray(new Foo[0]); or: Foo[] array = new Foo[list.size()]; list.toArray(array); // fill the array Note that this works only for arrays of reference types. For arrays of primitive types, use the traditional way: List<Integer> list = …; int[] array = new int[list.size()]; for(int i = 0; i < list.size(); i++) array[i] = … Read more
Actually, probably the “best” way to initialize the ArrayList is the method you wrote, as it does not need to create a new List in any way: ArrayList<String> list = new ArrayList<String>(); list.add(“A”); list.add(“B”); list.add(“C”); The catch is that there is quite a bit of typing required to refer to that list instance. There are … Read more
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
How to sort an ArrayList?
What’s the C++ version of Java’s ArrayList
Create ArrayList from array
“Exception in thread “main” java.lang.IndexOutOfBoundsException: Index: 0, Size: 0″ with ArrayList?
Java 8 introduces a String.join(separator, list) method; see Vitalii Federenko’s answer. Before Java 8, using a loop to iterate over the ArrayList was the only option: DO NOT use this code, continue reading to the bottom of this answer to see why it is not desirable, and which code should be used instead: ArrayList<String> list = new ArrayList<String>(); list.add(“one”); list.add(“two”); … Read more