java iterator 使用,多个If条件在Java中使用Iterator

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 list3)

{

Iterator 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 "||" ???

解决方案

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

This is NOT what you want to do I assume.

You should do this in stead:

Iterator 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.

This is handy for cases like this:

if (person == null || person.getName() == null) {

// do something

}

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值