您的位置:首页 > 其它

List在执行remove方法不能删除指定的对象

2017-05-22 22:07 330 查看

List在执行remove方法不能删除指定的对象

我们根据List中的源码分析,remove方法的原理:

public boolean remove(Object o){
if(o ==null) {
for(intindex=0;index< size;index++)
if(elementData[index] ==null) {
fastRemove(index);returntrue;
}
}else{
for(intindex=0;index< size;index++)
if(o.equals(elementData[index])) {
fastRemove(index);returntrue;
}
}
return false;
}


List在删除对象时,先判断这个对象是否在自己的队列中?而这种判断指的是是否equals;因此,List在删除对象时,如果使用删除对象方法,应该最好重写equals方法。或者采用删除下标的方法。

删除下标时一定要确保下标的类型是int类型,若是Integer类型,List会默认匹配remove(Object o)方法,而不是remove(int index)方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: