1

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

3
  • 1
    please include full stacktrace Commented Dec 12, 2012 at 2:30
  • 5
    Only call it.next() once per iteration. Commented Dec 12, 2012 at 2:30
  • As for the difference between | and ||, that's a topic for another question- although if you're particularly curious, a google search for "Bitwise Operator" may help you out. Commented Dec 12, 2012 at 2:32

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.