List对象remove方法的使用
来源:互联网 发布:淘宝店pc端怎么装修 编辑:程序博客网 时间:2024/06/05 20:07
一、源程序
String str1 = new String("1"); String str2 = new String("2"); String str3 = new String("3"); String str4 = new String("4"); String str5 = new String("5"); List list = new ArrayList(); list.add(str1); list.add(str2); list.add(str3); list.add(str4); list.add(str5); System.out.println("list.size()=" + list.size()); for (int i = 0; i < list.size(); i++) { list.remove(i); } System.out.println("after remove:list.size()=" + list.size());
本来预期结果应该是:
list.size()=5 after remove:list.size()=0
但实际上结果却是:
list.size()=5 after remove:list.size()=2
原因: List每remove掉一个元素以后,后面的元素都会向前移动 ,此时如果执行i++,则刚刚移过来的元素没有被读取。
二、分析:
List中有5条数据,需要循环5次,
第一次数据为:1 2 3 4 5
执行完remove(0) 后,数据为 2 3 4 5 , i=1
第二次数据为:2 3 4 5
执行完remove(1) 后,数据为 2 4 5 , i=2
第三次数据为:2 4 5
执行完remove(2) 后,数据为 2 4 , i=3 3 < list.size()=2 循环结束
三、解决方案
解决方法1:每移过一次后,再把 i 移回来
for (int i = 0; i < list.size(); i++) { System.out.println(i); list.remove(i); i--;}
解决方法2:先删除后面的元素
for (int i = list.size()-1; i >= 0; i--) { System.out.println(i); list.remove(i); }
解决方法3:iterator式删除(推荐)
Iterator it = list.iterator();while(it.hasNext()) { String str = (String) it.next();//next方法必须被调用,且必须在remove()方法前被执行 it.remove(); }
阅读全文
0 0
- List对象remove方法的使用
- List对象remove方法的使用
- list的remove方法
- List在执行remove方法不能删除指定的对象
- List循环使用remove()方法
- 使用List的Remove方法时想起的小问题
- List的remove方法误区
- 关于List的remove()方法
- 浅谈list的remove方法
- java.util.List的remove()方法使用技巧
- 使用List中remove方法时需要注意的问题
- java.util.List的remove()方法使用技巧(转)
- Java中list的remove方法移除的对象与下标重合了呢?
- 泛型List<T>中方法Remove不能删除对象的解决
- list.remove()时出问题,集合的remove方法注意事项
- Collection和List接口的remove方法
- 关于集合List的remove方法
- 关于java List的remove方法
- 剑指offer 孩子们的游戏(圆圈中最后剩下的数)
- The problem in Caffe Learning
- nginx+tomcat nginx 504 Gateway Time-out的方法
- Python初学之字典
- 卷积
- List对象remove方法的使用
- 暑假集训日记--8.2--搜索
- C++单链表的基本算法
- UE4_事件调度器
- python小白进阶三:主成分分析(PCA)
- day_14 C语言字符串处理和清空缓冲区
- JavaScript 创建对象的七种方式
- MySQL字符型数字比较大小
- bLue的苹果--有点坑