nivard
nivard

Reputation: 27

Multiple If conditions using Iterator in Java

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

Upvotes: 1

Views: 4796

Answers (2)

jahroy
jahroy

Reputation: 22692

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

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.

Upvotes: 6

Makoto
Makoto

Reputation: 106440

You want to avoid multiple calls to your iterator, as that advances it to the next element.

What you can do is preserve the value you get per iteration, then do your comparisons.

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

Upvotes: 1

Related Questions