有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

正确的做法是什么? 另外,使用“|”和“||”有什么区别


共 (2) 个答案

  1. # 1 楼答案

    您希望避免多次调用迭代器,因为这会使迭代器前进到下一个元素

    你能做的就是保留每次迭代得到的值,然后进行比较

    while(it.hasNext()) {
        Integer next = it.next();
        if(next == 2 || next == 3 || next == 5 || next == 7 ) {
            it.remove();
        }
    }
    
  2. # 2 楼答案

    每次调用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();
        }
    }
    

    |和| |之间的区别:

    如果使用||且第一部分为真,则不会对第二部分进行评估

    如果使用|,则始终会对这两个部分进行求值

    这对于这样的情况很方便:

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

    如果使用|且person为null,则上述代码段将抛出NullPointerException

    这是因为它将计算条件的两个部分,而第二部分将取消对空对象的引用