多个If条件在Java中使用Iterator [英] Multiple If conditions using Iterator in Java

查看:321
本文介绍了多个If条件在Java中使用Iterator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含元素1到10的列表。
我尝试从中删除素数2,3,5,7,然后使用iterator打印列表的其余部分。但是这个代码抛出 NoSuchElementException
这是我的代码:

I have a list which has elements 1 through 10. I try to remove the prime numbers 2,3,5,7 from it and then print the rest of the list using iterator.But this code throws a NoSuchElementException. this is my code :

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);
}

这样做的正确方法是什么?
也有使用|和||

What's the correct way of doing this? Also what's the difference between using "|" and "||" ???

推荐答案

每次调用 it.next()你的迭代器前进到下一个元素。

Each time you call it.next() your iterator advances to the next element.

这是你想做什么我假设。

This is NOT what you want to do I assume.

您应该这样做:

Iterator<Integer> it = list.iterator();

while (it.hasNext()) {
    Integer thisInt = it.next();
    if (thisInt == 2 || thisInt == 3 || thisInt == 5 || thisInt == 7) {
       it.remove();
    }
}






|之间的区别和||:



如果使用 || ,第一部分为真,


The difference between | and ||:

If you use || and the first part is true, then the 2nd part will not be evaluated.

如果使用 | ,将始终评估两个零件。

If you use | both parts will always be evaluated.

对于这种情况很方便:

if (person == null || person.getName() == null) {
    // do something
}

如果你使用 | 并且person为null,上面的代码段将抛出NullPointerException。

The above snippet would throw a NullPointerException if you used | and person was null.

的条件,而下半部分将取消引用一个空对象。

That's because it would evaluate both parts of the condition, and the second half would de-reference a null object.

这篇关于多个If条件在Java中使用Iterator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆