遍历删除元素,需要用迭代器
对于提供删除(remove)接口的集合(collection),需要在循环中删除某个元素,这样的做法是错误的:
1 List<String> names = ... 2 for (String name : names) { 3 if (name need to be removed) 4 names.remove(name); 5 }
remove某个元素会导致for取下个元素出错。正确的做法应该使用迭代器,
1 List<String> names = ... 2 Iterator<String> iter = names.iterator(); 3 while (iter.hasNext()) { 4 String str = iter.next(); 5 if (str need to be remove) 6 iter.remove(); 7 }