Learn Java Iterator – 3 Types of Iterator in Java

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

We discussed Java Virtual Machine in our last session. Here, we will talk about Java Iterator and how an 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 examples.

So, let us start with Java Iterators.

Java Iterator

Learn Java Iterator – 3 Types of Iterator in Java

What are iterators in Java?

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

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

Types of Java Iterators

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

Enumeration in Java

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

Do you know Why we use Assertion in Java

Syntax of Java Iterators –

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 in Java –

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

Limitations of Java Enumeration

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

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 the expelling capacity of an element.

Iterator must be utilized whenever we need to identify elements in all collection structure actualized interfaces like Set, List, Queue, Deque, and furthermore in every single executed class of the Map interface. Generally, Java iterators are the main cursor accessible for the whole collection Framework.
We can make an Iterator operator by calling the iterator() strategy shown in the 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]

Limitations of Java Iterator

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

ListIterator in Java

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

The use of ListIterator is to go through the list and perform various operations on it.

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 the listIterator() method, present in the List interface.

ListIterator ltr = l.listIterator();

It extends the Java iterator interface.

The 9 methods of listIterator in Java available are –

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

i. public Boolean hasNext() in Java

This method returns a Boolean value if there is another element present next to the element where the cursor is pointing. It returns true if the next element is present, otherwise false.

// same as next() method of Iterator

ii. Java 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() in Java

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

iv. public boolean hasPrevious() in Java

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

v. Java 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() in Java

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

vii. Java public void remove()

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

viii. public void set(Object obj) in Java

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

ix. Java 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. Therefore, 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:

1. UnsupportedOperationException: This exception arises when you have written the code to operate on the object, but it is against the object’s properties. For example, trying to update the array, but the size of the array doesn’t change; it remains fixed when it is created.

2. ClassCastException: If the class of the predetermined component keeps it from being added to this list.

3. IllegalArgumentException: If some part of the predetermined element keeps it from being added to this list.

4. IllegalStateException: If neither next nor past has been called, or expel or include have been called after the last call to previous or next. 

The add() strategy can toss three special cases:

1. UnsupportedOperationException: If they include a strategy that isn’t bolstered by this list.

2. ClassCastException: If the class of the predefined component keeps it from, add to this list.

3. 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 a list, not to a universal Java iterator.

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

Conclusion

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

See also – Java URL Class

For reference

Your opinion matters
Please write your valuable feedback about DataFlair 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 *