首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

使用List中remove方法时需要注意的有关问题

2012-12-25 
使用List中remove方法时需要注意的问题String str1 new String(1)String str2 new String(2)Str

使用List中remove方法时需要注意的问题

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);//i--;//System.out.println(i+" "+list.get(i)+" ");}System.out.println("after remove:list.size()=" + list.size());

?本来预期结果应该是:

list.size()=5after remove:list.size()=0

?但实际上结果却是:

list.size()=5after 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

此时如果加上上面注释的代码 System.out.println(i+" "+list.get(i)+" "); 循环第4、5次时就会出现异常

?

解决方法1:

?? 每移过一次后,再把 i 移回来

for (int i = 0; i < list.size(); i++) {list.remove(i);i--;}

?

解决方法2:

??? 先删除后面的元素

for (int i = list.size()-1; i >= 0; i--) {list.remove(i);    }

?解决方法3:

??? iterator式删除(貌似会有问题)

for(Iterator it = list.iterator();it.hasNext();){it.remove();}

?

部分参考:http://java.chinaitlab.com/base/821113.html

?

热点排行