java list 迭代中能否删除?

来源:互联网 发布:拉菲时时彩源码 编辑:程序博客网 时间:2024/05/21 08:53

看到同事写的一段code,说java可以在for 迭代过程中remove一个元素。太奇怪了,请看下面一段code, 居然没有抱错。

public class Solution {

  private void  test(){
    
        List<String> noWantedList = new ArrayList<String>(Arrays.asList(new String[] { "pm_data", "pmd",
                "gte.config",
                "systemfiles", "license","node_id", "node_identity.txt",
                "tmp", "logfiles", "configuration", "security",
                "public_html","usr" }));
            String test="security";
            for (String regex : noWantedList) {
        if(test.equals(regex))
        {
        noWantedList.remove("security");
        }
        return ; //here
        }
    }


public static void main(String[] args) {

Solution solution=new Solution();
solution.test();
}
}


这和我印象中只有用iterator 迭代过程中可以删除,而且只有用iter.remove()相矛盾呀。

经过仔细琢磨,原来上面代码能通过是在通过remove之后,直接就return了,没有继续迭代,所以才不抱错。

不过个人觉得还是不要在for 迭代过程中删除,这样的代码设计是不合理的。

0 0