How to add element in List while iterating in java?

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

    Iterate through a copy of the list and add new elements to the original list.

    for (String s : new ArrayList(list))     
    {
        list.add("u");
    }
    

    See How to make a copy of ArrayList object which is type of List?

提交回复
热议问题