Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need to use iterator on ArrayList in Java? [duplicate]

I was reading the answer mentioned to the question "Do we ever need to use Iterators on ArrayList?".

In the answer, the user stated something like this: "A big use case of iterators with ArrayLists is when you want to remove elements while iterating".

This could be achieved even using remove method of ArrayList in Java. My question is why we need iterator in ArrayList?

Consider the code:

import java.util.*; public class ocajp66 {     public static void main(String[] args) {         ArrayList a = new ArrayList();         for (int i = 0; i < 10; i++) {             a.add(i);         }         System.out.printf("BEFORE ITERATOR\n");         for (int i = 0; i < a.size(); i++) {             System.out.printf("I:%d\n", a.get(i));         }         System.out.printf("AFTER ITERATOR\n");         Iterator i = a.iterator();         while (i.hasNext()) {             System.out.printf("I:%d\n", i.next());         }     } } 

Can anybody explain the significance of the iterator? It would be wonderful if you could explain me with code.

like image 415
Karthik Rk Avatar asked Apr 14 '13 14:04

Karthik Rk


People also ask

Why iterator is used in ArrayList?

An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet. It is called an "iterator" because "iterating" is the technical term for looping. To use an Iterator, you must import it from the java.

Why do we need to use iterator in Java?

Iterator in Java is an object used to cycle through arguments or elements present in a collection. It is derived from the technical term “iterating,” which means looping through. Generally, an iterator in Java is used to loop through any collection of objects.

Can we use iterator in ArrayList?

The iterator can be used to iterate through the ArrayList wherein the iterator is the implementation of the Iterator interface. Some of the important methods declared by the Iterator interface are hasNext() and next().

What is iterator in ArrayList in Java?

The Java ArrayList iterator() method returns an iterator to access each element of the arraylist in a proper sequence. The syntax of the iterator() method is: arraylist.iterator()


1 Answers

As you have stated iterator is used when you want to remove stuff whilst you iterate over the array contents. If you don't use an iterator but simply have a for loop and inside it use the remove method you will get exceptions because the contents of the array changes while you iterate through. e.g: you might think array size is 10 at the start of the for loop but it wont be the case once you remove stuff.. so when u reach the last loops probably there will be IndexOutofBoundsException etc.

like image 120
Dev Blanked Avatar answered Sep 20 '22 03:09

Dev Blanked