今天项目需要将采集到List数据过滤,SoEasy!刷刷的写下了以下代码:
public static void main(String[] args) {
Filter filter = new Filter();
List<String> sss = new ArrayList<>();
sss.add("1");
sss.add("22");
sss.add("333");
sss.add("4444");
filter.filter(sss);
for (String ss : sss) {
System.out.println(ss);
}
}
public static class Filter {
/**
* @param source 传入的要过滤的源数据
* @return 将过滤后的数据返回
*/
public List<String> filter(List<String> source) {
for (String ss : source) {
if (ss.length() < 3) {
source.remove(ss);
}
}
return source;
}
}
一运行,结果
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at Main$Filter.filter(Main.java:37)
at Main.main(Main.java:25)
先说怎么解决,就是Itorator去处理,只贴fiter方法:
public List<String> filter(List<String> source) {
Iterator<String> iterator = source.iterator();
while (iterator.hasNext()) {
if (iterator.next().length() < 3) {
iterator.remove();
}
}
return source;
}
运行结果正确:
333
4444