Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. QQ discussion groups: 271934368 https://blog.csdn.net/huangjp_hz/article/details/78548595
notes
Sometimes knock Code encounter this situation, a circulation list, perform a complete removal of going after it, and then continue the cycle, if not pay attention to write easily run error: java.util.ConcurrentModificationException.
In reading "Java programming ideas" to see a good writing, could not help wondering record, here referred to as a method, in addition to a commonly used method, referred to as the second method, the following two methods Code:
method one
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
if (list.size() > 0){
for (String s:new ArrayList<>(list)){
System.out.println(s);
list.remove(s);
}
}
/*
Output : 1
2
3
*/
Method Two
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
if (list.size() > 0){
for (int i = list.size() - 1; i >= 0; i--){
System.out.println(list.get(i));
list.remove(i);
}
}
/*
Output : 3
2
1
*/
to sum up
Personally I prefer to use a method, but will not know what's hidden it ~