在Java中使用迭代器收集多个If条件
我有一个包含元素1到10的列表。 我尝试从中删除素数2,3,5,7,然后使用迭代器打印列表的其余部分。但是这段代码抛出了一个NoTouchElementException。 这是我的代码:
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);
}
正确的做法是什么? 另外,使用“|”和“||”有什么区别
# 1 楼答案
您希望避免多次调用迭代器,因为这会使迭代器前进到下一个元素
你能做的就是保留每次迭代得到的值,然后进行比较
# 2 楼答案
每次调用
it.next()
时,迭代器都会前进到下一个元素我想这不是你想做的事
你应该这样做,而不是:
|和| |之间的区别:
如果使用
||
且第一部分为真,则不会对第二部分进行评估如果使用
|
,则始终会对这两个部分进行求值这对于这样的情况很方便:
如果使用
|
且person为null,则上述代码段将抛出NullPointerException这是因为它将计算条件的两个部分,而第二部分将取消对空对象的引用