🌐
W3Schools
w3schools.com › java › java_iterator.asp
Java Iterator
To use an Iterator, you must import it from the java.util package.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Iterator.html
Iterator (Java Platform SE 8 )
July 21, 2026 - Removes from the underlying collection the last element returned by this iterator (optional operation). This method can be called only once per call to next(). The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › iterators-in-java
Iterator in Java - GeeksforGeeks
In contrast, ListIterator is bi-directional, allowing traversal in both directions. ... Example: Here, we will use an Iterator to traverse and remove odd elements from an ArrayList.
Published: 2 weeks ago
🌐
Baeldung
baeldung.com › home › java › java collections › a guide to iterator in java
A Guide to Iterator in Java | Baeldung
June 27, 2025 - In this example, we start by getting the ListIterator from the List, then we can obtain the next element either by index –which doesn’t increase the iterator’s internal current element – or by calling next.
🌐
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.
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › util › Iterator.html
Iterator (Java Platform SE 7 )
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 › iterator › java
Iterator in Java / Design Patterns
January 1, 2026 - package refactoring_guru.iterator.example.iterators; import refactoring_guru.iterator.example.profile.Profile; import refactoring_guru.iterator.example.social_networks.LinkedIn; import java.util.ArrayList; import java.util.List; public class LinkedInIterator implements ProfileIterator { private LinkedIn linkedIn; private String type; private String email; private int currentPosition = 0; private List<String> emails = new ArrayList<>(); private List<Profile> contacts = new ArrayList<>(); public LinkedInIterator(LinkedIn linkedIn, String type, String email) { this.linkedIn = linkedIn; this.type
🌐
Medium
medium.com › @AlexanderObregon › beginners-guide-to-java-iterators-e8d4eb19bf5d
Java Iterators Guide For Beginners | Medium
March 15, 2024 - Imagine you have a List of strings representing different types of fruits, and you wish to iterate over this list to print each fruit and remove a specific fruit from the list during the iteration. import java.util.ArrayList; import ...
Find elsewhere
🌐
Programiz
programiz.com › java-programming › iterator
Java Iterator Interface
In the example below, we have ... numbers.add(2); System.out.println("ArrayList: " + numbers); // Creating an instance of Iterator Iterator<Integer> iterate = numbers.iterator(); // Using the next() method int number = iterate.next(); System.out.println("Accessed Elem...
🌐
Jenkov
jenkov.com › tutorials › java-collections › iterator.html
Java Iterator
May 22, 2020 - As you can see, the example first iterates the ListIterator forward through all the elements, and then backwards again through all the elements back to the first element. If you have a special, custom made type of collection, you can implement the Java Iterator interface yourself to create an Iterator that can iterate through the elements of your custom collection.
🌐
BeginnersBook
beginnersbook.com › 2014 › 06 › java-iterator-with-examples
Java Iterator with examples
March 9, 2015 - The iterator is specifically designed for collection classes so it works well for all the classes in collection framework. Java iterator has some very useful methods, which are easy to remember and use.
🌐
DataCamp
datacamp.com › doc › java › iterator
Java Iterator
It is part of the Java Collections Framework and is found in the java.util package. The Iterator interface is used to access elements of a collection sequentially without exposing the underlying structure of the collection.
🌐
CodeGym
codegym.cc › java blog › java collections › java iterator
Java Iterator
January 16, 2025 - This does have its uses, but what happens if the collection doesn’t store elements in an index-based system? For example, Sets have no order normally. So it’s advisable to get out of the practice of using a for loop as an iterator in Java and practice using the Iterator<E> class instead.
🌐
Codecademy
codecademy.com › docs › java › iterator
Java | Iterator | Codecademy
July 31, 2025 - Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more. Beginner Friendly.Beginner Friendly17 hours17 hours ... remove(): Removes the last element returned by the iterator. Not all iterators support this operation. This example demonstrates the fundamental usage of an iterator to traverse through an ArrayList:
🌐
Mkyong
mkyong.com › home › java › java iterator examples
Java Iterator examples | mkyong.com
March 19, 2020 - List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); Iterator<Integer> iterator = list.iterator(); iterator.forEachRemaining(x -> { System.out.println(x * 2); }); ... package com.mkyong; import java.util.ArrayList; import java.util.Iterator; import ...
🌐
CodeJava
codejava.net › java-core › collections › how-to-use-iterator
How to use Iterator in Java - Iterator Examples with List, Set, Map and Queue
July 18, 2024 - List<String> listFruits = List.of("Apple", "Banana", "Lemon", "Dragon Fruit", "Durian"); listFruits.iterator().forEachRemaining(System.out::println);This method takes a parameter of type Consumer, which means you can pass a Lambda expression that results an object implementing that functional ...
Top answer
1 of 6
37

Variables

I understand why you have the Range.this.end and Range.this.start to avoid confusion about where those variables come from... If you need the Range.this as part of the teaching exercise, then sure. Otherwise, I would recommend three things....

  1. add range as a prefix, even though it is slightly redundant
  2. Make them final...
  3. one variable per line... (it makes revision-control diffs/patches easier to read)

The code would look like:

private final int rangeStart;
private final int rangeEnd;

Then, all the Range.this.start would be just rangeStart, etc.

Nested classes

Your iterator class is a non-static class, so it can reference the outer class's range start/end.

In this case, the nested class can be changed to a static class very easily. This has the potential of simplifying memory management because the iterator does not need a reference to the enclosing Range.

Consider a private-static Iterator instance:

// Inner class example
private static final class RangeIterator implements
                Iterator<Integer> {
    private int cursor;
    private final int end;

    public RangeIterator(int start, int end) {
        this.cursor = start;
        this.end = end;
    }

    public boolean hasNext() {
        return this.cursor < end;
    }

    public Integer next() {
        if(this.hasNext()) {
            int current = cursor;
            cursor ++;
            return current;
        }
        throw new NoSuchElementException();
    }

    public void remove() {
        throw new UnsupportedOperationException();
    }
}

This static class removes the need for the back-references to Range.this entirely....

The new iterator is called simply with:

public Iterator<Integer> iterator() {
    return new RangeIterator(start, end);
}

Pre-Validate

It is better to pre-validate state, than to fall-through to an error... This code:

    public Integer next() {
        if(this.hasNext()) {
            int current = cursor;
            cursor ++;
            return current;
        }
        throw new NoSuchElementException();
    }

would be better as:

    public Integer next() {
        if(!this.hasNext()) {
            throw new NoSuchElementException();
        }
        int current = cursor;
        cursor ++;
        return current;
    }

Post-Increment

This block can be simplified:

        int current = cursor;
        cursor ++;
        return current;

to just:

return cursor++;

although I imagine this is done as an education ploy.

Integer as the example

Because of the int autoboxing I worry that Integer may not be the right choice for data type. You may want to consider a non-primitive as the data.

Autoboxing is the sort of thing that will confuse.

Conclusion

Otherwise, I don't see much in the way of problems.

2 of 6
13

Overall, it's pretty good code to learn from.

Functionality

I like that you've used the inclusive-exclusive convention for the lower and upper bounds, respectively. The rationale for that design would be an interesting discussion topic.

I suggest adding a second constructor for convenience:

public Range(int end) {
    this(0, end);
}

There should probably be getters for start() and end(). Technically, you should override .equals() and .hashCode() as well, but maybe it's OK to leave them out for simplicity.

Style

As @rpg711 noted, putting the @Override annotation everywhere would be good practice. It would also help students see which methods are mandatory parts of the interface (well, practically all of them).

JavaDoc would be a good habit to teach. At the least, document the outer class and inner class, and probably their constructors as well.

It would be more conventional to put a space after the if, for, and while keywords. They look less like function calls that way.

Declaring start and end as final could help emphasize to students that the Range is immutable, and only the RangeIterator changes state. Perhaps adding final would alleviate some of @rolfl's concerns about the inner class referring to Range.this.start and Range.this.end.

In agreement with @rolfl, I would also personally prefer

    @Override
    public Integer next() {
        if (!this.hasNext()) {
            throw new NoSuchElementException();
        }
        // The post-increment magically takes effect _after_
        // returning.  This is equivalent to
        //
        //     int value = this.cursor++;
        //     return value;
        //
        return this.cursor++;
    }

… though I can understand if you choose not to burden the students with that trivia.

Test case

It would be useful to illustrate that two RangeIterators keep state independently. Perhaps this might make a good example?

Range digits = new Range(0, 10);
for (Integer tensDigit : digits) {
    for (Integer onesDigit : digits) {
        System.out.format("%s%s ", tensDigit, onesDigit);
    }
    System.out.println();
}
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-use-iterator-in-java
How to use Iterator in Java? - GeeksforGeeks
July 23, 2025 - ListIterator 'ListIterator' in Java is an Iterator which allows users to traverse Collection in both direction.
🌐
YouTube
youtube.com › jakob jenkov
Java Iterator - In Depth - YouTube
The Java Iterator interface represents a component that can iterate the elements of a Java collection. You can obtain a Java Iterator from a Java List, Java ...
Published: May 22, 2020
Views: 33K