FAQ

Java

JSP

Servlet


Advertisement



Why doesn't Iterator work for my collection?

Let's take a look at the following code:

class Program {
public static void main(String args[]) {
ArrayList<String> alist = new ArrayList<String>();
alist.add(new String("A"));
alist.add(new String("B"));
alist.add(new String("C"));
int i = 0;
for (Iterator<String> it = alist.iterator(); it.hasNext(); ) {
System.out.println(alist.get(i++));
}
}
}

A runtime exception java.lang.IndexOutOfBoundsException is thrown when it goes beyond the end.

What is wrong? The code combines the iterator and index. After hasNext() returns true, the only way to advance the iterator is to call next(). But the element is retrieved with get(index), so the iterator is never advanced. In the above example, the hasNext() will always be true, and eventually the index i for get(index) will beyond the end of ArrayList.

Do not mix up the iterator and the index. Let's change the above code to fix the problem:

class Program {
public static void main(String args[]) {
ArrayList<String> alist = new ArrayList<String>();
alist.add(new String("A"));
alist.add(new String("B"));
alist.add(new String("C"));
for (Iterator<String> it = alist.iterator(); it.hasNext(); ) {
System.out.println(it.next());
}
}
}

or

class Program {
public static void main(String args[]) {
ArrayList<String> alist = new ArrayList<String>();
alist.add(new String("A"));
alist.add(new String("B"));
alist.add(new String("C"));
for (int i=0; i != alist.size(); i++) {
System.out.println(alist.get(i));
}
}
}


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |