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.