public class IteratorDemo02{
public static void main(String args[]){
List<String> all= new ArrayList<String>() ; //
all.add("hello") ;
all.add("_") ;
all.add("world") ;
Iterator<String> iter = all.iterator() ; // 为Iterator接口实例化
while(iter.hasNext()){ // 判断是否有内容
String str = iter.next() ;
if("_".equals(str)){
iter.remove() ; // 删除元素 -------这里不要换成all.remove(str),否则循环执行完打印后,会跳出。不再向下执行。
}else{
System.out.println(str) ; // 输出内容
}
}
System.out.println("删除之后的集合:" + all) ;
}
};
也就是说在迭代里不要用collection里的remove方法,迭代自己有remove。但是一般开发中也不建议用的
输出结果:
hello
world
删除之后的集合:[hello, world]
如果用了all.remove(str) 则打印如下:
hello
删除之后的集合:[hello, world]
1729

被折叠的 条评论
为什么被折叠?



