我有两个列表嵌套for循环,当我匹配内部项目,我想要删除它,使性能会上升。如何删除列表中的项目?
List<String[]> brandList = readCsvFile("/tmp/brand.csv");
List<String[]> themeList = readCsvFile("/tmp/theme.csv");
for (String[] brand : brandList) {
for (String[] theme : themeList) {
if (brand[0].equals(theme[0])) {
themeList.remove(theme);
}
}
}
我得到了java.util.ConcurrentModificationException
错误。如果我改的CopyOnWriteArrayList,如下错误:
CopyOnWriteArrayList<String[]> themeList = (CopyOnWriteArrayList<String[]>)readCsvFile("/tmp/theme.csv");
java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.concurrent.CopyOnWriteArrayList
现在我该怎么办?省略删除?还是其他呢?
我觉得这是我需要的:
List<String[]> brandList = readCsvFile("/tmp/brand.csv");
List<String[]> themeList = readCsvFile("/tmp/theme.csv");
for (String[] brand : brandList) {
List<String[]> toRemove = new ArrayList<String[]>();
for (String[] theme : themeList) {
if (brand[0].equals(theme[0])) {
toRemove.add(theme);
}
}
for (String[] theme : toRemove) {
themeList.removeAll(theme);
}
}
你的代码是不是我想要的,我可以把themeList.removeAll(文档,删除);内外循环? – mikezang
将其放在循环外部会更有效,因为对所有要删除的元素只执行一次删除操作。这当然是可能的,但是从这段代码片断我看不出语义差异在哪里。 – chucktator
你的回答给了我想法,谢谢! – mikezang