• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

SoftwareTestingo - Jira Selenium Protractor Testing SDLC Agile Methodology

Java Selenium Tutorial & Testing Interview Questions

  • Home
  • Interview Questions
  • Java
  • Java Programs
  • Test Cases
  • Selenium
  • Manual Testing
  • Difference
  • Search
SoftwareTestingo » Java » Java Tutorial » Java Iterator In Details

Java Iterator In Details

Last Updated on: October 20, 2019 By Softwaretestingo Editorial Board

What We Are Learn On This Post

  • Different Types of Cursors
  • Enumeration
  • Drawbacks Of Enumeration
  • Java Iterator
  • Java Iterator Methods
  • Advantages of Iterator
  • Disadvantages of Iterator
  • ListIterator
  • Java ListIterator Methods
  • Advantages of listIterator
  • Disadvantages of ListIterator
  • Write a Program to Retrieve Element from List Iterator With Example?

Java iterator interface is used to iterate (loop) different elements of collection classes like HashMap, ArrayList, LinkedList, etc. In our previous post regarding Java Collection framework tutorial we are learned about different classes and interfaces like ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, HashMap, TreeMap, LinkedHashMap & Hashtable. But in this article, we are going to learn how to get the elements like one by one using different cursors of Java.

Different Types of Cursors

Before starting the different types of cursors, we have to know what a cursor is? A cursor nothing but an iterator which we used to iterate or traverse or retrieve the collection elements one by one.

Java programming language supports four different types of cursors:

  • Enumeration
  • Iterator
  • ListIterator
  • Spliterator

The above each iterator has some advantages and also some drawbacks. Let’s try to find the disadvantages and advantages one by one in detail.

Enumeration

This interface is used to get the elements of the legacy collections classes (Vector, Hashtable). This iterator is introduced in Java 100 version. Enumeration class is used to specify the input stream to a SequenceInputStream, and we can create an Enumeration object by calling elements() of the vector class.

This Enumeration class has mainly two classes:

  • Public boolean hasMoreElements(); For Test is the enumeration class has more elements or not.
  • public Object nextElement(); It returns the next elements of the enumeration, and if there are no more elements then it will throw NoSuchElementException
// Java program to demonstrate Enumeration
import java.util.Enumeration;
import java.util.Vector;

public class Test
{
   public static void main(String[] args)
   {
      // Create a vector and print its contents
      Vector v = new Vector();
      for (int i = 0; i < 10; i++)
         v.addElement(i);
      System.out.println(v);

      // At beginning e(cursor) will point to
      // index just before the first element in v
      Enumeration e = v.elements();

      // Checking the next element availability
      while (e.hasMoreElements())
      {
         // moving cursor to next element
         int i = (Integer)e.nextElement();

         System.out.print(i + ” “);
      }
   }
}

Drawbacks Of Enumeration

  • It is useful for only legacy classes like Vector and Hashtable.
  • Compare to the other iterators, method enumeration methods and names are lengthy, like hasMoreElements and nextElement.
  • It supports only forward direction, that’s why its also called uni-directional cursor.
  • As it supports legacy classes only its recommended not to use in the new projects.
  • It does not support CRUD operation. Enumeration only Supports the READ operation and does not support other operations like WRITE, UPDATE, AND DELETE.

Note: What is CRUD In Collection API?

  • CREATE: Adding new elements into the collection object.
  • READ Retrieving elements from the collection object.
  • UPDATE: Updating the existing element of the collection object.
  • DELETE: Removing the elements from the collection object.

Because of the above drawbacks in enumeration, Java comes up with another cursor in Java 1.2 that’s are Iterator and listIterator.

Java Iterator

Java iterator interface is present in the Java collection framework in Java.util package. You can use this iterator, which has implemented interfaces like Set, List, Queue, Deque, and also in all implemented classes of Map interface.

We can create the object of an iterator with the help of using iterator() of the collection interface.

Iterator itr = c.iterator();
  • This iterator is used to retrieve collection objects one by one.
  • This iterator is introduced in Java 1.2 version.
  • It applies to all collection objects. That’s why it also called as Universal iterator.
  • It Supports Both READ and REMOVE operations.
  • Compare to the enumeration method name iterator method names is simple.

Java Iterator Methods

It has three methods to operate with the elements of an iterator, that’s are:

  • hasNext() – Returns true if the iteration have the next elements
  • next() – It returns the next elements of the iteration and throws NoSuchElementException when there are no more elements
  • Remove () – This method helps in removing the elements from the iteration. This method can be called once per call to the next() method. when you are using this method, you may get two different types of exception that are

UnsupportedOperationException: If the remove operation is not supported by the iterator, in that case, you will get such type of exception.
IllegalStateException: If the next method is not called or the remove method is called once after that, if you try to execute again the remove() method that time, you will get this type of error.

// Java program to demonstrate Iterator
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);

      // at beginning itr(cursor) will point to
      // index just before the first element in al
      Iterator itr = al.iterator();

      // checking the next element availabilty
      while (itr.hasNext())
      {
         // moving cursor to next element
         int i = (Integer)itr.next();

         // getting even elements one by one
         System.out.print(i + ” “);

         // Removing odd elements
         if (i % 2 != 0)
            itr.remove();
      }
      System.out.println();
      System.out.println(al);
   }
}

Advantages of Iterator

As compare to the enumeration java iterator have the below advantages:

  • We can use it in any collection class.
  • It Supports both READ and REMOVE operation
  • It’s a Universal cursor.
  • Method names are simple and easy to use.

Disadvantages of Iterator

Still, there are some disadvantages of Iterator like below:

  • It does not support CRUD operation fully, like Update and create operation is not supported.
  • You can access the forward elements of a collection class — that why this is a unidirectional cursor.

To overcome such a problem, Java programming language has introduced one more new type of cursor in Java 1.2 version that is ListIterator.

ListIterator

Like Iterator, this also used to retrieve elements from collection class, but it’s for list implemented objects.

We can create a listIterator object by following the below syntax:

// Where l is any List Object
ListIterator ltr = l.listIterator();
  • It extends the Iterator interface.
  • It is implemented for the List to implement the interface.
  • It supports all four types of CRUD operation, like CREATE, READ, UPDATE AND DELETE
  • It supports both forward and Backward direction iterations, that’s why this is called bidirectional iterator.
  • ListIterator does not have a current location, and its cursor always lies in between the element that would be returned by a call to previous() and the element that would be replaced by a call to next()

Java ListIterator Methods

  • public boolean hasNext(); this method returns true if the iteration has more elements.
  • Public Object next(); Returns the next element of the iterator
  • public int nextIndex(); Returns the next element index. If the cursor is at the last position, then it will return the list size.
  • Public boolean hasPrevious(); Returns true if the iteration has more elements when traversing in the backward direction.
  • Public Object previous(); These methods return the previous elements, and if there are no more elements then it will throw a NoSuchElementException
  • public int previousIndex(); It will return the last index element and -1 if the cursor is beginning of the list
  • public void remove(); It will remove the elements from the collection
  • Public void set(Object obj); this method helps when you want to replace the element which is provided by the next() or previous() method with a specified element.
  • public void add(Object obj); By using this, you can insert your element into the collection before the position which is returned by next() method

When you try to use Set() & add() method, you may get below exceptions:

  • UnsupportedOperationException: If the list iterator does not support the set operation.
  • ClassCastException: If the class of the specified element is not allowed to add into the list
  • IllegalArgumentException: Due to some reason if some specified element prevents it from adding into the list.
  • IllegalStateException: If neither next nor previous have been called, or remove or add have been called after the last call to next or previous
// Java program to demonstrate ListIterator
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);

      // at beginning ltr(cursor) will point to
      // index just before the first element in al
      ListIterator ltr = al.listIterator();

      // checking the next element availabilty
      while (ltr.hasNext())
      {
         // moving cursor to next element
         int i = (Integer)ltr.next();

         // getting even elements one by one
         System.out.print(i + ” “);

         // Changing even numbers to odd and
         // adding modified number again in
         // iterator
         if (i%2==0)
         {
            i++; // Change to odd
            ltr.set(i); // set method to change value
            ltr.add(i); // to add
         }
      }
      System.out.println();
      System.out.println(al);
   }
}

Advantages of listIterator

  • It supports CRUD operation fully like CREATE, READ, UPDATE AND DELETE
  • By using this, you can traverse both forward and backward direction, so its also called a bidirectional cursor.

Disadvantages of ListIterator

  • You can use this iterator only with the List implemented classes, but like an iterator, you can not use it with all collection API.

Write a Program for Retrieve Elements Using Iterator In Collection?

package com.java.Softwaretestingblog;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class MyCollectionIterator {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      List<String> myList = new ArrayList<String>();
      myList.add("Java");
      myList.add("Unix");
      myList.add("Oracle");
      myList.add("C++");
      myList.add("Perl");
      Iterator<String> itr = myList.iterator();
      while(itr.hasNext())
      {
         System.out.println(itr.next());
      }
   }
}

Execution: The final output link

Output:

Java
Unix
Oracle
C++
Perl

Ref: article

ListIterator Example

Write a Program to Retrieve Element from List Iterator With Example?

package com.java.Softwaretestingblog;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class MyListIterator {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      List<Integer> li = new ArrayList<Integer>(); 
      ListIterator<Integer> litr = null; 
      li.add(23); 
      li.add(98); 
      li.add(29); 
      li.add(71); 
      li.add(5); 
      litr=li.listIterator(); 
      System.out.println("Elements in forward directiton"); 
      while(litr.hasNext())
      {
         System.out.println(litr.next()); 
      }
      System.out.println("Elements in backward directiton"); 
      while(litr.hasPrevious())
      {
         System.out.println(litr.previous()); 
      }
   }
}

Execution: The Final Output link

Output:

Elements in forward directiton
23
98
29
71
5
Elements in backward directiton
5
71
29
98
23

Iterator Example: How to Print Iterate LinkedHashSet Elements In Java With Example?

package com.java.Softwaretestingblog;
import java.util.Iterator;
import java.util.LinkedHashSet;
public class LinkedHashSetIteratorExample {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      LinkedHashSet<String> lhs = new LinkedHashSet<String>();
      //add elements to HashSet
      lhs.add("first");
      lhs.add("second");
      lhs.add("third");
      Iterator itr = lhs.iterator();
      while(itr.hasNext()){
         System.out.println(itr.next());
      }
   }
}

Output:

first
second
third

Java iterator Uses In Java Program: How to Add & Retrieve From HashSet Using Java iterator?

Check Also: Common Element Between Two Array
package com.java.Softwaretestingblog;
import java.util.HashSet;
import java.util.Iterator;
public class IteratorExample {
   public static void main(String[] args)
   {
      HashSet<String> hs = new HashSet<String>();
      //add elements to HashSet
      hs.add("first");
      hs.add("second");
      hs.add("third");
      Iterator<String> itr = hs.iterator();
      while(itr.hasNext())
      {
         System.out.println(itr.next());
      }
   }
}

Execution: Learn more about how you can execute the program link

Output:

third
first
second

Reference: Article

    Filed Under: Java Tutorial

    Reader Interactions

    Leave a Reply Cancel reply

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

    Primary Sidebar

    Join SoftwareTestingo Telegram Group

    Tutorials Important Links

    • Software Testing Jobs
    • Manual Testing Tutorial
    • Selenium Tutorial
    • Core Java Tutorial
    • TestNG Tutorial
    • Java Programs
    • Selenium Programs
    • Manual Test Cases
    • Interview Tips
    • Contact US
    • www.softwaretestingo.com

    Important Links

    • Software Testing Interview Questions
    • Agile Interview Questions
    • Manual Testing Interview Questions
    • Testing Interview Questions
    • Selenium Interview Questions
    • Selenium Real Time Interview Questions
    • Selenium WebDriver Interview Questions
    • Automation Framework Interview Questions
    • Appium Interview Questions
    • TestNG Interview Questions
    • Java Interview Questions
    • Core Java Interview Questions

    Categories

    Copyright © 2021 SoftwareTestingo.com ~ Contact Us ~ Sitemap ~ Privacy Policy