OCJP Exam watch tip #17


// This program shows the usage of Iterator
import java.util.ArrayList;
import java.util.Iterator;
class TestIterator {
    public static void main(String []args) {
        ArrayList<Integer> nums = new ArrayList<Integer>();
        for(int i = 1; i < 10; i++)
        System.out.println(“Original list ” + nums);

      Iterator<Integer> numsIter = nums.iterator();
      while(numsIter.hasNext()) {
      System.out.println(“List after removing all elements” + nums);

It prints the following:
Original list [1, 2, 3, 4, 5, 6, 7, 8, 9]
Exception in thread “main” java.lang.IllegalStateException
at java.util.AbstractList$Itr.remove(AbstractList.java:356)
at TestIterator.main(Main.java:12)

The problem is that next() was not called before calling remove() . Checking hasNext() in the while loop condition, moving to the element using next() , and calling remove()
is the correct idiom for removing an element. If you don’t follow it correctly, you can get into trouble (i.e., you’ll get IllegalStateException ).




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s