Learn Java Iterator – 3 Types of Iterator in Java

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

1. Objective

We discussed Java Virtual Machine in our last session. Here, we will talk about Java Iterator and how iterator works in java. Along with this, we will discuss enumeration with its example, and syntax. Also, we will see Java Iterator and ListIterators with their limitation and example.

So, let us start Java Iterators.

Java Iterator

Learn Java Iterator – 3 Types of Iterator in Java

2. What is Iterators in Java?

Basically, Java Iterators are used in Java for retrieving the elements one by one, they are used in Collection Framework and allow us:

  • To traverse the collection
  • Access the Data Elements
  • Delete the Element

3. Types of Java Iterators

Here, we are going to study three types of iterators in Java, let’s discuss them one by one:

a. Enumeration

It is an interface used to get components of inheritance collections (Vector, Hashtable). Enumeration is the principal Java iterator introduce from JDK 1.0, rests incorporate into JDK 1.2 with greater usefulness. Enumerations are additionally use for determining the information streams to a SequenceInputStream. We can make Enumeration object by calling elements() method for vector class on any vector object.

Do you know Why we use Assertion in Java

Syntax –

Enumeration e = v.elements();
The two methods in enumeration interface are –
// Tests if this enumeration contains more elements
public boolean hasMoreElements();
// Returns the next element of this enumeration
// It throws NoSuchElementException
// if no more element present
public Object nextElement();

Example of Enumeration –

import java.util.Enumeration;
import java.util.Vector;
public class Test
{
   public static void main(String[] args)
   {
       Vector v = new Vector();
       for (int i = 0; i < 10; i++)
           v.addElement(i);
       System.out.println(v);
       Enumeration e = v.elements();
       while (e.hasMoreElements())
       {
           int i = (Integer)e.nextElement();
           System.out.print(i + " ");
      }
   }
}

Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0 1 2 3 4 5 6 7 8 9

i. Limitations of Enumeration

  • It is for a legacy class, and hence not a universal Java iterator.
  • The operations of removing cannot be performed.
  • Only forward iteration is possible.

b. Java Iterator

It is a general (universal) Java iterator as we can apply it to any collection object. By utilizing Java Iterator, we can perform both read and remove operations. It is an enhanced variant of Enumeration with the extra usefulness of expelling capacity of an element.

Iterator must be utilized at whatever point we need to identify elements in all collection structure actualized interfaces like Set, List, Queue, Deque and furthermore in every single executed class of Map interface. Generally, Java iterator is the main cursor accessible for whole collection Framework.
We can make an Iterator operator by calling iterator() strategy show in Collection interface.

A Syntax of Java Iterator –

Iterator itr = c.iterator();
It basically has three methods –
// Returns true if the iteration has more elements
public boolean hasNext();
// Returns the next element in the iteration
// It throws NoSuchElementException if no more
// element present
public Object next();
// Remove the next element in the iteration
// This method can be called only once per call
// to next()
public void remove();
  • The remove iterator can throw two exceptions –

UnsupportedOperationException and IllegalStateException

Java Date and Time – Java Date Class & GregorianCalendar Class

import java.util.ArrayList;
import java.util.Iterator;
public class Test
{
   public static void main(String[] args)
   {
       ArrayList al = new ArrayList();
       for (int i = 0; i < 10; i++)
           al.add(i);
       System.out.println(al);
       Iterator itr = al.iterator();
       while (itr.hasNext())
       {
           int i = (Integer)itr.next();
                       System.out.print(i + " ");
           if (i % 2 != 0)
              itr.remove();
       }
       System.out.println();
       System.out.println(al);
   }
}

Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0 1 2 3 4 5 6 7 8 9
[0, 2, 4, 6, 8]

i. Limitations

  • Iteration of only forward direction is possible.
  • Replacement and addition not possible.

c. ListIterator

This is only applicable where there is List implemented classes such as ArrayList, linked list etc. It provides the user to give bi-directional iteration, it is used when we want to enumerate the list, it has more functionality.

Read Java Array Tutorial – Creating, Initializing, and Accessing Array in Java

Java Iterator

Java Iterator- List Iterator

Generally, we can create the list by using listIterator() method, present in List interface.

ListIterator ltr = l.listIterator();

It extends the Java iterator interface.

The 9 methods available are –

// Forward direction
// Returns true if the iteration has more elements

i. public Boolean hasNext()

// same as next() method of Iterator

ii. public Object next()

// Returns the next element index
// or list size as required if the list iterator
// is at the end of the list

iii. public int nextIndex()

// Backward direction
// Returns true if the iteration has more elements
// while traversing backward

iv. public booleeam hasPrevious()

// Returns the previous element in the iteration
// and can throws NoSuchElementException
// if no more element present

v. public Object previous()

// Returns the previous element index
//  or -1 if the list iterator is at the
// beginning of the list

Let’s explore Java Method – Declaration and Calling a Java Method

vi. public int previousIndex()

// Other Methods
// same as remove() method of Iterator

vii. public void remove()

// Replaces the last element returned by
// next() or previous() with the specified element

viii. public void set(Object obj)

// Inserts the specified element into the list at
// position before the element that would be returned
// by next(),

ix. public void add(Object obj)

Obviously, the three techniques that ListIterator acquires or inherits from Iterator (hasNext(), next(), and remove()) do the very same thing in the two interfaces. The hasPrevious() and the past tasks are correct analogs of hasNext() and next(). The previous tasks allude to the component before the (implicit) cursor, though the last allude to the component after the cursor. The past activity moves the cursor in reverse, though next advances it.

Literals in Java – Integral, Floating, Char, String, Boolean

Hence, ListIterator has no present component; its cursor position dependably lies between the element that would return by a call to previous() and the component that would return by a call to next()

set() technique can toss four special cases

  • UnsupportedOperationException: If the set task isn’t bolstered by this list iterator.
  • ClassCastException: If the class of the predetermined component keeps it from being added to this list.
  • IllegalArgumentException: If some part of the predetermined element keeps it from being added to this list.
  • IllegalStateException: If neither next nor past have been called, or expel or include have been called after the last call to previous or next.

add() strategy can toss three special cases

  • UnsupportedOperationException: If they include strategy isn’t bolster by this list Java iterator
  • ClassCastException: If the class of the predefined component keeps it from, add to this list.
  • IllegalArgumentException: If some part of this component keeps it from, add to this list.
import java.util.ArrayList;
import java.util.ListIterator;
public class Test
{
   public static void main(String[] args)
   {
       ArrayList al = new ArrayList();
       for (int i = 0; i < 10; i++)
           al.add(i);
       System.out.println(al);
       ListIterator ltr = al.listIterator();
       while (ltr.hasNext())
       {
           int i = (Integer)ltr.next();
           System.out.print(i + " ");
           if (i%2==0)
           {
               i++;
               ltr.set(i);
               ltr.add(i);         }
       }
       System.out.println();
       System.out.println(al);
   }
}

Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0 1 2 3 4 5 6 7 8 9
[1, 1, 1, 3, 3, 3, 5, 5, 5, 7, 7, 7, 9, 9, 9]

  • Only applicable to list not to a universal Java iterator.

So, this was all about Java Iterator. Hope you like our explanation.

4. Conclusion

Hence, in this Java tutorial, we studied the Java Iterator. In conclusion, we discussed Java Iterators in Java, Enumeration, ListIterators with their example, limitation and syntax. Along with this, we saw several methods for java Iterator. Furthermore, if you have any query, feel free to ask through the comment section.

See also – Java URL Class

For reference

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

courses

DataFlair Team

DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.

Leave a Reply

Your email address will not be published. Required fields are marked *