写法一:
Iterator<QcSampleDTO> it = qclist.iterator();
//排除尾箱容器
while (it.hasNext()) {
if(it.next().getContainerId().equals(tailDTO.getContainerId())
&& it.next().getLotId().equals(tailDTO.getLotId())) {
it.remove();
}
}
出现了两次 it.next() ,如果list集合长度为2,就不会第二次进入遍历。
写法二:
QcSampleDTO tailDTO = tailList.get(0);
Iterator<QcSampleDTO> it = qclist.iterator();
//排除尾箱容器
while (it.hasNext()) {
QcSampleDTO sampleDTO = it.next();
if (sampleDTO.getContainerId().equals(tailDTO.getContainerId())
&& sampleDTO.getLotId().equals(tailDTO.getLotId())) {
it.remove();
}
}
写法一是个坑,it.next()使用一次,下标加一,写法二正确。

本文探讨了在Java中使用Iterator遍历集合并删除元素的两种不同写法,指出了一种常见陷阱及其正确处理方式。错误的方法会导致遍历异常终止,而正确的方法则能安全地完成元素的移除。
2166

被折叠的 条评论
为什么被折叠?



