动态删除ArrayList中的元素


 1 ArrayList删除元素后长度变小了,元素的索引也会跟着改变,但是迭代的下标没有跟着相应的改变的缘故。

  将一些删除方法做一些总结:

/** 2 * 删除Arraylist中值为"c"的元素 3 */ 4 public static void main(String[] args) { 5 6 List<String> list = new ArrayList<String>(); 7 8 //"c"在Arraylist不连续存储 9 /* 10 list.add("c"); 11 list.add("a"); 12 list.add("c"); 13 list.add("b"); 14 list.add("c"); 15 list.add("d"); 16 list.add("c"); 17 */ 18 19 //"c"在Arraylist有连续存储 20 list.add("a"); 21 list.add("c"); 22 list.add("c"); 23 list.add("b"); 24 list.add("c"); 25 list.add("c"); 26 list.add("d"); 27 list.add("c"); 28 29 30 //删除Arraylist中值为"c"的元素 31 32 //有可能不能全部删除 33 //removeListElement1(list); 34 35 //能够正确删除 36 //removeListElement2(list); 37 38 //能够正确删除 39 //removeListElement3(list); 40 } 41 42 43 /** 44 * 删除list中值为"c"的元素 45 * 46 * 这种方式: 47 * 48 * 当值为"c"的元素在Arraylist中不连续存储的时候,是可以把值为"c"的元素全部删掉 49 * 50 * 但是当值为"c"的元素在Arraylist中有连续存储的时候,就没有把值为"c"的元素全部删除 51 * 因为删除了元素,Arraylist的长度变小了,索引也会改变,但是迭代的下标没有跟着变小 52 */ 53 public static void removeListElement1(List<String> list) { 54 for(int i=0;i<list.size();i++) { 55 if("c".equals(list.get(i))) { 56 list.remove(i); 57 } 58 } 59 60 } 61 62 /** 63 * 删除Arraylist中值为"c"的元素 64 * 65 * 这种方式: 66 * 67 * 不管值为"c"的元素在Arraylist中是否连续,都可以把值为"c"的元素全部删除 68 */ 69 public static void removeListElement2(List<String> list) { 70 for(int i=0;i<list.size();i++) { 71 if("c".equals(list.get(i))) { 72 list.remove(i); 73 --i;//删除了元素,迭代的下标也跟着改变 74 } 75 } 76 } 77 78 /** 79 * 删除Arraylist中值为"c"的元素 80 * 81 * 这种方式: 82 * 83 * 不管值为"c"的元素在list中是否连续,都可以把值为"c"的元素全部删除 84 * 85 * 需保证没有其他线程同时在修改 86 */ 87 public static void removeListElement3(List<String> list) { 88 Iterator<String> iterator = list.iterator(); 89 while(iterator.hasNext()) { 90 String str = iterator.next(); 91 if("c".equals(str)) { 92 iterator.remove(); 93 } 94 95 } 96 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值