java的remove iterator_Java迭代器Iterator的remove()方法的使用

遍历Java集合(Arraylist,HashSet...)的元素时,可以采用Iterator迭代器来操作

Iterator接口有三个函数,分别是hasNext(),next(),remove()。

今天浅谈remove函数的作用

官方解释为:

Removes from the underlying collection the last element returned by this iterator (optional operation). This method can be called only once per call to next(). The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.

译:从底层集合中移除此迭代器返回的最后一个元素(可选操作)。 每次调用next()时,只能调用此方法一次。 如果在迭代正在进行中以除调用此方法之外的任何方式修改基础集合,则未指定迭代器的行为。

官方说法现在先不研究

举个例子1:在使用迭代器遍历集合的过程中,使用集合对象的remove方法删除数据时,查看迭代器的运行情况。

Listall = new ArrayList();

all.add("a");

all.add("b");

all.add("c");

Iteratoriterator=all.iterator();//实例化迭代器

while(iterator.hasNext()){

String str=iterator.next();//读取当前集合数据元素

if("b".equals(str)){

all.remove(str);

}else{

System.out.println( str+" ");

}

}

System.out.println("\n删除\"b\"之后的集合当中的数据为:"+all);

输出结果为:fc896b7a0b944346869125d4b13baef1.png

发现:使用集合对象 all 的 remove() 方法后,迭代器的结构被破坏了,遍历停止了。

------------------

举个例子2:在使用迭代器遍历集合的过程中,使用迭代器的 remove 方法删除数据时,查看迭代器的运行情况

Listall = new ArrayList();

all.add("a");

all.add("b");

all.add("c");

Iteratoriterator = all.iterator();//实例化迭代器

while(iterator.hasNext()){

String str=iterator.next();//读取当前集合数据元素

if("b".equals(str)){

//all.remove(str);//使用集合当中的remove方法对当前迭代器当中的数据元素值进行删除操作(注:此操作将会破坏整个迭代器结构)使得迭代器在接下来将不会起作用

iterator.remove();

}else{

System.out.println( str+" ");

}

}

System.out.println("\n删除\"b\"之后的集合当中的数据为:"+all);

运行结果70e0078aabe84b538c591adaadbf2667.png

发现:使用迭代器 的 remove() 方法后,迭代器删除了当前读取的元素 “b”,并且继续往下遍历元素,达到了在删除元素时不破坏遍历的目的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值