niv*_*ard 0 java collections iterator
我有一个列表,其中包含元素1到10.我尝试从中删除素数2,3,5,7然后使用iterator打印列表的其余部分.但此代码抛出 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);
}
Run Code Online (Sandbox Code Playgroud)
这样做的正确方法是什么?还有什么区别使用"|" 和"||" ???
每次调用it.next()
迭代器前进到下一个元素.
这不是我想要做的.
你应该这样做:
Iterator<Integer> it = list.iterator();
while (it.hasNext()) {
Integer thisInt = it.next();
if (thisInt == 2 || thisInt == 3 || thisInt == 5 || thisInt == 7) {
it.remove();
}
}
Run Code Online (Sandbox Code Playgroud)
如果您使用||
且第一部分为true,则不会评估第二部分.
如果使用|
这两个部件将始终进行评估.
这对于这样的情况很方便:
if (person == null || person.getName() == null) {
// do something
}
Run Code Online (Sandbox Code Playgroud)
如果您使用了|
person并且person为null,则上面的代码段将抛出NullPointerException .
那是因为它会评估条件的两个部分,而后半部分将取消引用null对象.