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

来源:互联网 发布:淘宝双十一红包群 编辑:程序博客网 时间:2024/05/22 15:24

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)方法。

原创粉丝点击