【发布时间】:2012-11-29 16:34:13
【问题描述】:
我有一个包含元素 1 到 10 的列表。 我尝试从中删除素数 2、3、5、7,然后使用迭代器打印列表的其余部分。但此代码抛出 NoSuchElementException。 这是我的代码:
public static void editerate2(Collection<Integer> list3)
{
Iterator<Integer> it=list3.iterator();
while(it.hasNext())
{
if(it.next()==2 || it.next()==3 || it.next() ==5 || it.next()==7 )
{
it.remove();
}
}
System.out.println("List 3:");
System.out.println("After removing prime numbers : " + list3);
}
这样做的正确方法是什么? 还有使用“|”有什么区别和“||” ???
【问题讨论】:
-
请包含完整的堆栈跟踪
-
每次迭代只调用一次
it.next()。 -
至于
|和||之间的区别,这是另一个问题的主题——尽管如果你特别好奇,谷歌搜索“位运算符”可能会对你有所帮助。
标签: java collections iterator