您的位置:首页 > 编程语言 > Java开发

java 中List 集合删除元素

2014-03-24 18:09 555 查看
今天做一个排班的功能;
设计的时候需要实现从一个list集合中  删除一个object的操作;
for (HumanWorkTime hwt: hwtList) {
if (hwt.getId().equals(tempId)) {
hwtList.remove(hwt);
}
}

然后就抛出了错误;

SEVERE: Servlet.service() for servlet [spring] in context with path [/edu] threw exception [Request processing failed; nested exception is java.util.ConcurrentModificationException] with root cause
java.util.ConcurrentModificationException


理论上应该没错呀;

dubug;

发现 代码hwtList.remove(hwt) 并没有抛出错误;

纳闷。。。

逐句查看 发现是在执行过hwtList.remove(hwt)之后, 进入下一个循环的时候 抛错,

仔细观察了一下 , 发现执行过删除操作后 list的size发生改变

恍然大悟, 肯定是集合的长度改变引起的, 所以改成下面的代码,运行通过

for(int i = 0, len = hwtList.size(); i < len; i++) {
if (hwtList.get(i).getId().equals(tempHwId)){
hwtList.remove(hwtList.get(i));
len--;
i--;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: