关于List,ArrayList中remove(object obj)方法不能删除对象问题
来源:互联网 发布:支持php的web服务器 编辑:程序博客网 时间:2024/05/01 18:23
参考文章:
http://blog.csdn.net/ws992077171/article/details/7856433
先看下面代码,大家猜猜打印的结果是什么?为什么?
package shiyan; import java.util.ArrayList; import java.util.List; public class ListTest { public static void main(String[] args) { // TODO Auto-generated method stub List<A> list = new ArrayList<A>(); A a1 = newA(1,"a1"); A a2 = newA(2,"a2"); A a3 = newA(3,"a3"); A a4 = newA(4,"a4"); A a5 = newA(5,"a5"); list.add(a1); list.add(a2); list.add(a3); list.add(a4); list.add(a5); list.remove(a2); System.out.println(list.size()); } } class A{ int id; String name; public A(int id,String name){ this.id = id; this.name = name; } public boolean equals(Object obj) { return false; } }
如果您的回答是:4,我想您就有必要看看本文了,因为正确答案是5
先贴上:ArrayList上的remove源码:
public boolean remove(Object o) { if(o == null) { for(int index = 0; index < size; index++) if(elementData[index] == null) { fastRemove(index); return true; } }else{ for(int index = 0; index < size; index++) if(o.equals(elementData[index])) { fastRemove(index); return true; } } return false; }
看源码可知,List在删除对象时,先判断这个对象是否在自己的队列中?而这种判断指的是是否equals
因此,List在删除对象时,如果使用删除对象方法,应该最好重写equals方法,否则最好使用删除下标的方法。
注:删除下标时一定要确保下标的类型是int类型,若是Integer类型,List会默认匹配remove(Object o)方法,而不是remove(int index)方法。
0 0
- 关于List,ArrayList中remove(object obj)方法不能删除对象问题
- 关于List,ArrayList中remove(object obj)方法不能删除对象问题
- List在执行remove方法不能删除指定的对象
- 泛型List<T>中方法Remove不能删除对象的解决
- C#中 List类型Remove()方法不能移除对象问题
- List调用remove(object);方法无法删除!
- 关于用集合的remove方法删除list集合中满足条件的元素问题
- ArrayList中add(Object obj)方法的注意事项
- 关于 list.remove(obj);方法在迭代器中报java.util.ConcurrentModificationException
- list.remove(object)问题
- 【Android】ArrayList通过remove方法删除元素对象源码分析
- java中ArrayList的remove方法删除一个数据时问题简述
- 关于JAVA中使用remove方法循环删除list中元素的常见误区
- 解决list.remove(object)问题
- ArrayList的add(Object obj)和remove(Object obj)和remove(index)和get(index)的源码分析
- ArrayList中remove()方法删除长度大于5的元素之后下标重定位的问题
- List中remove方法
- 关于List<object>中按对象的某个属性值排序的方法
- ionic
- 【LeetCode231算法/编程练习C++】--判断是否是2的整数次幂 //按位与&的用处
- MyWebSQL - Draft
- 417. Pacific Atlantic Water Flow
- LaunchScreen.storyboard: The document “(null)” requires Xcode 8.0 or later
- 关于List,ArrayList中remove(object obj)方法不能删除对象问题
- 魔术索引II
- arcpy实现重排地块号
- 服务器请求微信后台(api.weixin.qq.com)过慢处理
- 质量控制之室内质控(IQC)和室间质评(EQA)
- 仿京东天猫的下拉刷新
- (十六)备忘录模式详解(都市异能版)
- 还有 13 天,苹果就要关上 HTTP 大门了
- java中的4种访问修饰符