When to use a linked list over an array/array list?

Linked lists are preferable over arrays when: you need constant-time insertions/deletions from the list (such as in real-time computing where time predictability is absolutely critical) you don’t know how many items will be in the list. With arrays, you may need to re-declare and copy memory if the array grows too big you don’t need … Read more

Java ArrayList how to add elements at the beginning

List has the method add(int, E), so you can use: list.add(0, yourObject); Afterwards you can delete the last element with: if(list.size() > 10) list.remove(list.size() – 1); However, you might want to rethink your requirements or use a different data structure, like a Queue EDIT Maybe have a look at Apache’s CircularFifoQueue: CircularFifoQueue is a first-in … Read more

How to randomize two ArrayLists in the same fashion?

Use Collections.shuffle() twice, with two Random objects initialized with the same seed: long seed = System.nanoTime(); Collections.shuffle(fileList, new Random(seed)); Collections.shuffle(imgList, new Random(seed)); Using two Random objects with the same seed ensures that both lists will be shuffled in exactly the same way. This allows for two separate collections.

Java ArrayList copy

Yes, assignment will just copy the value of l1 (which is a reference) to l2. They will both refer to the same object. Creating a shallow copy is pretty easy though: List<Integer> newList = new ArrayList<>(oldList); (Just as one example.)

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

Java List.add() UnsupportedOperationException

Not every List implementation supports the add() method. One common example is the List returned by Arrays.asList(): it is documented not to support any structural modification (i.e. removing or adding elements) (emphasis mine): Returns a fixed-size list backed by the specified array. Even if that’s not the specific List you’re trying to modify, the answer … Read more