Say I have a List like:
List list = new ArrayList<>();
list.add(\"a\");
list.add(\"h\");
list.add(\"f\");
list.add(\"s\");
I do this by adding the elements to an new, empty tmp List, then adding the tmp list to the original list using addAll()
. This prevents unnecessarily copying a large source list.
Imagine what happens when the OP's original list has a few million items in it; for a while you'll suck down twice the memory.
In addition to conserving resources, this technique also prevents us from having to resort to 80s-style for loops and using what are effectively array indexes which could be unattractive in some cases.