How to add element in List while iterating in java?

前端 未结 5 896
暖寄归人
暖寄归人 2020-12-15 16:25

Say I have a List like:

List list = new ArrayList<>();
list.add(\"a\");
list.add(\"h\");
list.add(\"f\");
list.add(\"s\");
5条回答
  •  温柔的废话
    2020-12-15 16:44

    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.

提交回复
热议问题