Let's take a look at the following code:
class Program { public static void main(String args[]) { ArrayListalist = new ArrayList (); alist.add(new String("A")); alist.add(new String("B")); alist.add(new String("C")); int i = 0; for (Iterator 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[]) { ArrayListalist = new ArrayList (); alist.add(new String("A")); alist.add(new String("B")); alist.add(new String("C")); for (Iterator it = alist.iterator(); it.hasNext(); ) { System.out.println(it.next()); } } }
or
class Program { public static void main(String args[]) { ArrayListalist = new ArrayList (); 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)); } } }
Comments
Post a Comment