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

Convert list to array in Java [duplicate]

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

Initialization of an ArrayList in one line

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

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

Best way to convert an ArrayList to a string

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