🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Iterator.html
Iterator (Java Platform SE 8 )
July 21, 2026 - Iterator takes the place of Enumeration in the Java Collections Framework. Iterators differ from enumerations in two ways: 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.
🌐
GeeksforGeeks
geeksforgeeks.org › java › iterator-interface-in-java
Iterator Interface In Java - GeeksforGeeks
July 23, 2025 - Java Iterator Interface of java collections allows us to access elements of the collection and is used to iterate over the elements in the collection(Map, List or Set). It helps to easily retrieve the elements of a collection and perform operations ...
🌐
W3Schools
w3schools.com › java › java_iterator.asp
Java Iterator
Java Examples Java Videos Java ... Study Plan Java Interview Q&A ... An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet....
🌐
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.
🌐
Programiz
programiz.com › java-programming › iterator
Java Iterator Interface
All the Java collections include an iterator() method. This method returns an instance of iterator used to iterate over elements of collections. The Iterator interface provides 4 methods that can be used to perform various operations on elements of collections.
🌐
Oracle
docs.oracle.com › en › java › javase › 11 › docs › api › java.base › java › util › Iterator.html
Iterator (Java SE 11 & JDK 11 )
January 20, 2026 - Iterator takes the place of Enumeration in the Java Collections Framework. Iterators differ from enumerations in two ways: 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.
🌐
Baeldung
baeldung.com › home › java › java collections › differences between iterator and iterable and how to use them?
Differences Between Iterator and Iterable and How to Use Them? | Baeldung
June 27, 2025 - Iterator is a member of the Java Collections Framework. It belongs to the java.util package. This interface allows us to retrieve or remove elements from a collection during the iteration.
Find elsewhere
🌐
University of Washington
courses.cs.washington.edu › courses › cse373 › 24wi › projects › maps › iterator
Iterator Interface - CSE 373
You may access the full list of Java’s Interface Iterator · for more detail. An iterator is a type of object that lets a client efficiently iterate over a data structure using a forEach loop. Whenever we write code like: for (String item : something) { // ...etc...
🌐
DataCamp
datacamp.com › doc › java › iterator
Java Iterator
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. It is part of the Java Collections Framework and is found in the java.util package.
🌐
Medium
medium.com › @Neelesh-Janga › iterator-and-iterable-in-java-java-stories-be23f2b73125
Iterator and Iterable in Java — Java Stories | Neelesh J | Medium
July 7, 2024 - The Iterable interface acts as a root interface for all collection classes in Java. It defines a single method, iterator(), which allows objects to be iterated using the enhanced for-loop (foreach loop) or manually with an Iterator object.
🌐
Reddit
reddit.com › r/javahelp › is my understanding of iterators and iterable correct?
r/javahelp on Reddit: Is my understanding of Iterators and Iterable correct?
April 23, 2019 -

Hi,

According to my understanding of Iterator and Iterable:

  1. Iterable is used when you want to get for - each for a collection. Iterator is still used behind the scenes to fetch the items for for-each.

  2. If I just want to go through a collection ( don't want for-each) , I can just implement Iterator interface on collection class and it should work. Note - Iterable is not necessary.

  3. If I implement Iterator interface on a collection class, It gives me the ability to iterate over the collection . Now if I implement the 'for-each' method (defined in Iterable Interface ) in the class , then I can get a for-each loop for the collection , even without implementing Iterable.

is it correct?

Thanks

Top answer
1 of 4
6
Iterable is a functional interface that outlines what an iterator is. Iterator is an interface that outlines methods to be used in the iterator. Java Collections come with iterators, which means they implement Iterable already. You can make your own data structure and define an iterator for it if you like. Iterable is used when you want to get for - each for a collection. Iterator is still used behind the scenes to fetch the items for for-each. An iterator is used to get the items. That iterator is created by using the Iterator interface [ ie- Iterator itr = yourList.iterator() ]. That data structure (list) implements Iterable, which is why it has an iterator() method. If I just want to go through a collection ( don't want for-each) , I can just implement Iterator interface on collection class and it should work. Note - Iterable is not necessary. You're confused as to what Iterable, Iterator, and iterator() do. If you want to iterate through a Collection without using a for-each style implementation, use the good ole for loop. If I implement Iterator interface on a collection class, It gives me the ability to iterate over the collection . Now if I implement the 'for-each' method (defined in Iterable Interface ) in the class , then I can get a for-each loop for the collection , even without implementing Iterable. Is this a question? Iterable is already implemented in every Java Collection.
2 of 4
3
The for-each statement (for(var element : elements)...) can iterate over the elements of arrays or, via an Iterator the elements of an Iterable. Whilst you do not have to implement Iterable (that is, you can just supply an iterator), it's trivially easy to do so. If you implement Iterator iterator() and Iterable then you get forEach(Consumer) for free as it's a default method of Iterable - though you could choose to implement a more efficient option that doesn't use an iterator at all. If you're implementing a java.util.Collection class then you have no choice but to also implement Iterable as it is a sub-interface of Iterable.
🌐
W3Schools
w3schools.com › java › java_collections.asp
Java Collections Framework
The Java Collections Framework provides the List, Set, Map, and Queue types behind ArrayList and HashMap.
Top answer
1 of 16
18

Why is this interface used?

Because it supports the basic operations that would allow a client programmer to iterate over any kind of collection (note: not necessarily a Collection in the Object sense).

Why are the methods... not directly coded to the data structure implementation itself?

They are, they're just marked Private so you can't reach into them and muck with them. More specifically:

  • You can implement or subclass an Iterator such that it does something the standard ones don't do, without having to alter the actual object it iterates over.
  • Objects that can be traversed over don't need to have their interfaces cluttered up with traversal methods, in particular any highly specialized methods.
  • You can hand out Iterators to however many clients you wish, and each client may traverse in their own time, at their own speed.
  • Java Iterators from the java.util package in particular will throw an exception if the storage that backs them is modified while you still have an Iterator out. This exception lets you know that the Iterator may now be returning invalid objects.

For simple programs, none of this probably seems worthwhile. The kind of complexity that makes them useful will come up on you quickly, though.

2 of 16
6

You ask: "Why are the methods hasNext(), next() and remove() not directly coded to the data structure implementation itself?".

The Java Collections framework chooses to define the Iterator interface as externalized to the collection itself. Normally, since every Java collection implements the Iterable interface, a Java program will call iterator to create its own iterator so that it can be used in a loop. As others have pointed out, Java 5 allows us to direct usage of the iterator, with a for-each loop.

Externalizing the iterator to its collection allows the client to control how one iterates through a collection. One use case that I can think of where this is useful is when one has an an unbounded collection such as all the web pages on the Internet to index.

In the classic GoF book, the contrast between internal and external iterators is spelled out quite clearly.

A fundamental issue is deciding which party conrols the iteration, the iterator or the client that uses the iterator. When the client controls the iteration, the iterator is called an external iterator, and when the iterator controls it, the iterator is an internal iterator. Clients that use an external iterator must advance the traversal and request the next element explicitly from the iterator. In contrast, the client hands an internal iterator an operation to perform, and the iterator applies that operation to every element ....

External iterators are more flexible than internal iterators. It's easy to compare two collections for equality with an external iterator, for example, but it's practically impossible with internal iterators ... But on the other hand, internal iterators are easier to use, because they define the iteration logic for you.

For an example of how internal iterators work, see Ruby's Enumerable API, which has internal iteration methods such as each. In Ruby, the idea is to pass a block of code (i.e. a closure) to an internal iterator so that a collection can take care of its own iteration.

🌐
Software Testing Help
softwaretestinghelp.com › home › java tutorial for beginners: 100+ hands-on java video tutorials › java iterator: learn to use iterators in java with examples
Java Iterator: Learn To Use Iterators In Java With Examples
April 1, 2025 - In order to use an Iterator, you need to get the iterator object using the “iterator()” method of the collection interface. Java Iterator is a collection framework interface and is a part of the “java.util” package.
🌐
Refactoring.Guru
refactoring.guru › design-patterns › behavioral-patterns
Behavioral Design Patterns
Turns a request into a stand-alone object that contains all information about the request. This transformation lets you pass requests as a method arguments, delay or queue a request's execution, and support undoable operations. Iterator
🌐
Career Ride
careerride.com › Java-class-what-is-Iterator-interface.aspx
What is an Iterator interface?
What is an Iterator interface? - An iterator acts over a collection like an Enumeration. However, Iterators differ from enumerations in two ways:...
🌐
TheServerSide
theserverside.com › tip › Iterator-vs-ListIterator-Which-interface-should-you-choose
Iterator vs. ListIterator: Which interface should you choose? | TheServerSide
The Java Iterator is an all-purpose interface that simplifies looping through a collection of objects.
Published: November 18, 2021
🌐
Scaler
scaler.com › home › topics › java › iterable interface in java
Iterable Interface in Java - Scaler Topics
April 27, 2024 - Java Iterator supports only Sequential transversal. We cannot skip elements or visit only even or odd positions in a collection. The for-each loop is slower as for every iteration it calls the iterator() method. Any class implementing an Iterable Interface overrides the iterator() method, which returns an Iterator that allows the user to iterate through that class's collection.
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().

import 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...

public 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:

// 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.

🌐
Simplilearn
simplilearn.com › home › resources › software development › everything you need to know about iterator in java
Everything You Need to Know About Iterator in Java
June 14, 2026 - Iterator in java is used to cycle through elements present in a collection. Learn about ✔️collection framework ✔️methods ✔️uses of iterator in java, and more.
Address: 5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States