【问题标题】:Multiple If conditions using Iterator in Java在 Java 中使用 Iterator 的多个 If 条件
【发布时间】: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


【解决方案1】:

每次调用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,上述 sn-p 将抛出 NullPointerException。

这是因为它将评估条件的两个部分,而后半部分将取消引用空对象。

【讨论】:

    【解决方案2】:

    您希望避免多次调用您的迭代器,因为这会将其推进到下一个元素。

    可以做的是保留每次迭代获得的值,然后进行比较。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-02
      • 2019-05-17
      • 1970-01-01
      • 2021-04-06
      • 1970-01-01
      • 2019-03-01
      • 1970-01-01
      • 2021-08-16
      相关资源
      最近更新 更多