The best reusable option is to implement the interface Iterable and override the method iterator().

Here's an example of a an ArrayList like class implementing the interface, in which you override the method Iterator().

Copyimport java.util.Iterator;

public class SOList<Type> implements Iterable<Type> {

    private Type[] arrayList;
    private int currentSize;

    public SOList(Type[] newArray) {
        this.arrayList = newArray;
        this.currentSize = arrayList.length;
    }

    @Override
    public Iterator<Type> iterator() {
        Iterator<Type> it = new Iterator<Type>() {

            private int currentIndex = 0;

            @Override
            public boolean hasNext() {
                return currentIndex < currentSize && arrayList[currentIndex] != null;
            }

            @Override
            public Type next() {
                return arrayList[currentIndex++];
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
        return it;
    }
}

This class implements the Iterable interface using Generics. Considering you have elements to the array, you will be able to get an instance of an Iterator, which is the needed instance used by the "foreach" loop, for instance.

You can just create an anonymous instance of the iterator without creating extending Iterator and take advantage of the value of currentSize to verify up to where you can navigate over the array (let's say you created an array with capacity of 10, but you have only 2 elements at 0 and 1). The instance will have its owner counter of where it is and all you need to do is to play with hasNext(), which verifies if the current value is not null, and the next(), which will return the instance of your currentIndex. Below is an example of using this API...

Copypublic static void main(String[] args) {
    // create an array of type Integer
    Integer[] numbers = new Integer[]{1, 2, 3, 4, 5};

    // create your list and hold the values.
    SOList<Integer> stackOverflowList = new SOList<Integer>(numbers);

    // Since our class SOList is an instance of Iterable, then we can use it on a foreach loop
    for(Integer num : stackOverflowList) {
        System.out.print(num);
    }

    // creating an array of Strings
    String[] languages = new String[]{"C", "C++", "Java", "Python", "Scala"};

    // create your list and hold the values using the same list implementation.
    SOList<String> languagesList = new SOList<String>(languages);

    System.out.println("");
    // Since our class SOList is an instance of Iterable, then we can use it on a foreach loop
    for(String lang : languagesList) {
        System.out.println(lang);
    }
}
// will print "12345
//C
//C++
//Java
//Python
//Scala

If you want, you can iterate over it as well using the Iterator instance:

Copy// navigating the iterator
while (allNumbers.hasNext()) {
    Integer value = allNumbers.next();
    if (allNumbers.hasNext()) {
        System.out.print(value + ", ");
    } else {
        System.out.print(value);
    }
} 
// will print 1, 2, 3, 4, 5

The foreach documentation is located at http://download.oracle.com/javase/1,5.0/docs/guide/language/foreach.html. You can take a look at a more complete implementation at my personal practice google code.

Now, to get the effects of what you need I think you need to plug a concept of a filter in the Iterator... Since the iterator depends on the next values, it would be hard to return true on hasNext(), and then filter the next() implementation with a value that does not start with a char "a" for instance. I think you need to play around with a secondary Interator based on a filtered list with the values with the given filter.

Answer from Marcello DeSales on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Iterator.html
Iterator (Java Platform SE 8 )
1 month ago - Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics. Method names have been improved. This interface is a member of the Java Collections Framework.
🌐
W3Schools
w3schools.com › java › java_iterator.asp
Java Iterator
Java Examples Java Videos Java ... Interview Q&A Java Certificate ... An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet....
Discussions

Can we write our own iterator in Java? - Stack Overflow
If I have a list containing [alice, bob, abigail, charlie] and I want to write an iterator such that it iterates over elements that begin with 'a', can I write my own ? How can I do that ? More on stackoverflow.com
🌐 stackoverflow.com
loops - Understanding Java Iterator - Stack Overflow
If I run the following code, it will print out 3 times duplicate, but when I remove the if statement inside the while loop (just to see how many times it will iterate) it starts an infinite loop. ... More on stackoverflow.com
🌐 stackoverflow.com
What are the benefits of using an iterator in Java - Stack Overflow
If this example is not relevant, what would be a good situation when we should use the Iterator? ... For one thing, the for-each loop is neither plain nor old: it was officially introduced as the "enhanced for loop" in Java 5. More on stackoverflow.com
🌐 stackoverflow.com
What are Iterators? What are they useful for?
Iterators are just special objects that allow you to "walk" or "traverse" over a collection of data. The iterator has methods like hasNext() and next() to determine IF there is another item in your collection and to get the next one. This allows you to not be concerned with how your data is stored but just that you want to "iterate" or got through each item. More on reddit.com
🌐 r/javahelp
15
10
March 15, 2018
🌐
GeeksforGeeks
geeksforgeeks.org › java › iterators-in-java
Iterator in Java - GeeksforGeeks
Iterator is a universal cursor that applies to most collection types such as List, Set, and Queue. Although Map is part of the Java Collections Framework, it is not a subtype of the Collection interface.
Published   March 11, 2026
🌐
Medium
medium.com › @AlexanderObregon › beginners-guide-to-java-iterators-e8d4eb19bf5d
Java Iterators Guide For Beginners | Medium
March 15, 2024 - This abstraction is crucial because it allows developers to write code that is independent of the collection type they are working with, whether it’s an ArrayList, LinkedList, HashSet, or any other collection that implements the Iterable interface. The beauty of Java iterators lies in their simplicity and the power they offer in navigating through collections.
Top answer
1 of 6
215

The best reusable option is to implement the interface Iterable and override the method iterator().

Here's an example of a an ArrayList like class implementing the interface, in which you override the method Iterator().

Copyimport java.util.Iterator;

public class SOList<Type> implements Iterable<Type> {

    private Type[] arrayList;
    private int currentSize;

    public SOList(Type[] newArray) {
        this.arrayList = newArray;
        this.currentSize = arrayList.length;
    }

    @Override
    public Iterator<Type> iterator() {
        Iterator<Type> it = new Iterator<Type>() {

            private int currentIndex = 0;

            @Override
            public boolean hasNext() {
                return currentIndex < currentSize && arrayList[currentIndex] != null;
            }

            @Override
            public Type next() {
                return arrayList[currentIndex++];
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
        return it;
    }
}

This class implements the Iterable interface using Generics. Considering you have elements to the array, you will be able to get an instance of an Iterator, which is the needed instance used by the "foreach" loop, for instance.

You can just create an anonymous instance of the iterator without creating extending Iterator and take advantage of the value of currentSize to verify up to where you can navigate over the array (let's say you created an array with capacity of 10, but you have only 2 elements at 0 and 1). The instance will have its owner counter of where it is and all you need to do is to play with hasNext(), which verifies if the current value is not null, and the next(), which will return the instance of your currentIndex. Below is an example of using this API...

Copypublic static void main(String[] args) {
    // create an array of type Integer
    Integer[] numbers = new Integer[]{1, 2, 3, 4, 5};

    // create your list and hold the values.
    SOList<Integer> stackOverflowList = new SOList<Integer>(numbers);

    // Since our class SOList is an instance of Iterable, then we can use it on a foreach loop
    for(Integer num : stackOverflowList) {
        System.out.print(num);
    }

    // creating an array of Strings
    String[] languages = new String[]{"C", "C++", "Java", "Python", "Scala"};

    // create your list and hold the values using the same list implementation.
    SOList<String> languagesList = new SOList<String>(languages);

    System.out.println("");
    // Since our class SOList is an instance of Iterable, then we can use it on a foreach loop
    for(String lang : languagesList) {
        System.out.println(lang);
    }
}
// will print "12345
//C
//C++
//Java
//Python
//Scala

If you want, you can iterate over it as well using the Iterator instance:

Copy// navigating the iterator
while (allNumbers.hasNext()) {
    Integer value = allNumbers.next();
    if (allNumbers.hasNext()) {
        System.out.print(value + ", ");
    } else {
        System.out.print(value);
    }
} 
// will print 1, 2, 3, 4, 5

The foreach documentation is located at http://download.oracle.com/javase/1,5.0/docs/guide/language/foreach.html. You can take a look at a more complete implementation at my personal practice google code.

Now, to get the effects of what you need I think you need to plug a concept of a filter in the Iterator... Since the iterator depends on the next values, it would be hard to return true on hasNext(), and then filter the next() implementation with a value that does not start with a char "a" for instance. I think you need to play around with a secondary Interator based on a filtered list with the values with the given filter.

2 of 6
51

Sure. An iterator is just an implementation of the java.util.Iterator interface. If you're using an existing iterable object (say, a LinkedList) from java.util, you'll need to either subclass it and override its iterator function so that you return your own, or provide a means of wrapping a standard iterator in your special Iterator instance (which has the advantage of being more broadly used), etc.

🌐
Tutorialspoint
tutorialspoint.com › java › java_using_iterator.htm
Java - How to Use Iterator?
Java Vs. C++ ... Often, you will want to cycle through the elements in a collection. For example, you might want to display each element. The easiest way to do this is to employ an iterator, which is an object that implements either the Iterator or the ListIterator interface.
Find elsewhere
🌐
Refactoring.Guru
refactoring.guru › home › design patterns › iterator › java
Iterator in Java / Design Patterns
January 1, 2026 - Iterator pattern in Java. Full code example in Java with detailed comments and explanation. Iterator is a behavioral design pattern that allows sequential traversal through a complex data structure without exposing its internal details.
🌐
Baeldung
baeldung.com › home › java › java collections › creating custom iterator in java
Creating Custom Iterator in Java | Baeldung
June 27, 2025 - An Iterator<E> is an interface in the Java Collections framework and provides methods that allow traversing through a collection. An Iterator instance can be obtained by calling the iterator() method on a Collection, such as a List, Set, and ...
🌐
Baeldung
baeldung.com › home › java › java collections › a guide to iterator in java
A Guide to Iterator in Java | Baeldung
June 27, 2025 - An Iterator is one of many ways we can traverse a collection, and as every option, it has its pros and cons. It was first introduced in Java 1.2 as a replacement of Enumerations and:
🌐
CodeGym
codegym.cc › java blog › java collections › java iterator
Java Iterator
January 16, 2025 - It also includes the various interfaces for those classes, such as Set, List, Queue, Dequeue, and Sorted Set, to name a few. Iterator<E> is the public interface method of the Interface Iterator<E> class. It was brought about in Java 1.2 and replaced Enumeration as a way to examine sequential elements in a collection.
🌐
Medium
medium.com › @toimrank › java-iterator-1cc0dbce8e95
Java Iterator. Iterator interface belongs to java.util… | by Imran Khan | Medium
October 10, 2022 - Iterator interface allows us to iterate over collection of different class objects such as ArrayList, HashSet etc.
🌐
Lean Tactic Reference
course.ccs.neu.edu › cs2510sp18 › lecture25.html
Lecture 25: Iterator and Iterable
The while loop sketch above will work with any object that exposes these two functions as methods. This is a promise to provide a certain set of behaviors, so we should accordingly define a new interface. This interface is called an Iterator, and it is provided for us by Java itself.
🌐
DataCamp
datacamp.com › doc › java › iterator
Java Iterator
Java keywordsIntroduction To JavaJava File HandlingJava Language BasicsJava ArraysJava Object-Oriented Programming ... The Iterator in Java is an interface that provides a way to traverse through a collection of objects, such as lists or sets, one element at a time.
🌐
Oracle
docs.oracle.com › en › java › javase › 21 › docs › api › java.base › java › util › Iterator.html
Iterator (Java SE 21 & JDK 21)
January 20, 2026 - Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics. Method names have been improved. This interface is a member of the Java Collections Framework.
🌐
Refactoring.Guru
refactoring.guru › home › design patterns › behavioral patterns
Iterator
January 1, 2026 - The main idea of the Iterator pattern is to extract the traversal behavior of a collection into a separate object called an iterator.
🌐
Oracle
docs.oracle.com › en › java › javase › 22 › docs › › api › java.base › java › util › Iterator.html
Iterator (Java SE 22 & JDK 22)
July 16, 2024 - Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics. Method names have been improved. This interface is a member of the Java Collections Framework.
🌐
Jenkov
jenkov.com › tutorials › java-collections › iterator.html
Java Iterator
May 22, 2020 - The Java Iterator interface represents an object capable of iterating through a collection of Java objects one object at a time. This Java Iterator tutorial explains how to use the Iterator interface.