ArrayList在remove时遇到的坑

  今日在使用ArrayList的remove方法时,使用了以下代码:

 for(int res : list){
 	if(res == key){
		list.remove(res);
	}
 }
  • 然后发现在用list的contains()方法时,总是返回true,检查代码怎么都查不到原因,结果是因为在循环遍历ArrayList时直接像上述中使用删除remove方法会出错!

  所以在在循环遍历ArrayList中使用remove方法需要使用以下方法:

public void method(int key){
	Iterator<Integer> it = list.iterator();
        while (it.hasNext()){
            if (it.next() == key) {
                it.remove();
            }
        }
}

猜你喜欢

转载自blog.csdn.net/harryshumxu/article/details/104356973