| Java FAQ | ||
| JSP FAQ | ||
| Servlet FAQ | ||
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 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));
}
}
}
|