How to add element in List while iterating in java?

前端 未结 5 933
暖寄归人
暖寄归人 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:45

    You could iterate on a copy (clone) of your original list:

    List copy = new ArrayList(list);
    for (String s : copy) {
        // And if you have to add an element to the list, add it to the original one:
        list.add("some element");
    }
    

    Note that it is not even possible to add a new element to a list while iterating on it, because it will result in a ConcurrentModificationException.

提交回复
热议问题