Course Content
Core Java
About Lesson

Iterator

The Iterator interface in Java is used to iterate over elements in a collection. It provides methods for sequentially accessing elements of a collection and is part of the java.util package.

It allows sequential access to elements in a collection without exposing the underlying implementation of the collection. Typically used with collections like ArrayList, LinkedList, HashSet, etc., to traverse and access elements.

Methods

boolean hasNext() : Returns true if there are more elements in the collection, otherwise returns false.

E next() : Returns the next element in the collection. Throws NoSuchElementException if there are no more elements (hasNext() returns false).

void remove() : Removes from the underlying collection the last element returned by next(). Throws IllegalStateException if next() has not been called, or if remove() has already been called after the last call to next().

default void forEachRemaining(Consumer<? super E> action) : Performs the given action for each remaining element until all elements have been processed or the action throws an exception.

Example Code

import java.util.ArrayList;
import java.util.Iterator;

public class IteratorExample {
    public static void main(String[] args) {
        // Create an ArrayList of Strings
        ArrayList<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        fruits.add("Dates");

        // Obtain an iterator from the ArrayList
        Iterator<String> iterator = fruits.iterator();

        // Traverse the ArrayList using Iterator
        while (iterator.hasNext()) {
            String fruit = iterator.next();
            System.out.println(fruit);

            // Remove "Banana" from the ArrayList using Iterator's remove method
            if (fruit.equals("Banana")) {
                iterator.remove();
            }
        }

        // Print the modified ArrayList after removal
        System.out.println("ArrayList after removal:");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

Code to implement custom Iterator

import java.util.Iterator;

public class CustomList implements Iterable<Integer> {
    private int[] elements;
    private int size;
    
    public CustomList(int capacity) {
        elements = new int[capacity];
        size = 0;
    }
    
    public void add(int element) {
        if (size < elements.length) {
            elements[size++] = element;
        } else {
            // Handle array resizing or throw an exception
            // Here we assume the array won't overflow for simplicity
            System.err.println("Array capacity exceeded.");
        }
    }
    
    @Override
    public Iterator<Integer> iterator() {
        return new CustomListIterator();
    }
    
    // Custom Iterator implementation
    private class CustomListIterator implements Iterator<Integer> {
        private int currentIndex = 0;
        
        @Override
        public boolean hasNext() {
            return currentIndex < size;
        }
        
        @Override
        public Integer next() {
            if (!hasNext()) {
                throw new IndexOutOfBoundsException("No more elements to iterate.");
            }
            return elements[currentIndex++];
        }
        
        @Override
        public void remove() {
            throw new UnsupportedOperationException("Remove operation is not supported.");
        }
    }
    
    public static void main(String[] args) {
        CustomList list = new CustomList(5);
        list.add(10);
        list.add(20);
        list.add(30);
        
        // Iterate through elements using the custom iterator
        Iterator<Integer> iterator = list.iterator();
        while (iterator.hasNext()) {
            int element = iterator.next();
            System.out.println("Element: " + element);
        }
    }
}

Enumeration

In Java, Enumeration is an interface used to iterate through elements in a collection. It predates the more versatile Iterator interface and is typically associated with older Java collections like Vector and Hashtable. While Iterator is the preferred choice for iterating over collections in modern Java programming, understanding Enumeration is beneficial for maintaining legacy codebases.

Unlike Iterator, Enumeration does not have a method to remove elements from the underlying collection (Iterator has remove() method).

Iterator supports concurrent modification detection (ConcurrentModificationException), but Enumeration does not.

Methods

boolean hasMoreElements() : Returns true if there are more elements in the collection, otherwise returns false.

E nextElement() : Returns the next element in the collection. Throws NoSuchElementException if there are no more elements (hasMoreElements() returns false).

import java.util.Enumeration;
import java.util.Vector;

public class EnumerationExample {
    public static void main(String[] args) {
        // Create a Vector of Strings
        Vector<String> colors = new Vector<>();
        colors.add("Red");
        colors.add("Green");
        colors.add("Blue");

        // Obtain an Enumeration from the Vector
        Enumeration<String> enumeration = colors.elements();

        // Traverse the Vector using Enumeration
        while (enumeration.hasMoreElements()) {
            String color = enumeration.nextElement();
            System.out.println(color);
        }
    }
}

Scroll to Top