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));
}
}
}
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?