Skip to content

Instantly share code, notes, and snippets.

@wfwei
Created June 27, 2013 09:58
Show Gist options
  • Select an option

  • Save wfwei/5875335 to your computer and use it in GitHub Desktop.

Select an option

Save wfwei/5875335 to your computer and use it in GitHub Desktop.
java容器,遍历的同时删除元素
ArrayList<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
System.out.println(list.size());
// This will fail
// for (String item : list) {
// list.remove(item);
// }
Iterator<String> iter = list.iterator();
while (iter.hasNext()) {
String a = iter.next();
iter.remove();
System.out.println("removed " + a);
}
System.out.println(list.size());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment