Skip to content

spotbugs reports IT_NO_SUCH_ELEMENT for infinite iterator #3501

@hgschmie

Description

@hgschmie

consider this code:

class ConstantIterator<T> implements Iterator<T> {
    private final T value;

    private ConstantIterator(T value) {
        this.value = value;
    }

    @Override
    public boolean hasNext() {
        return true;
    }

    @Override
    public T next() {
        return value;
    }
}

This is a fine iterator. However, spotbugs reports

[ERROR] Medium: ConstantIterator.next() cannot throw NoSuchElementException [ConstantIterator] At ConstantIterator.java:[line 17] IT_NO_SUCH_ELEMENT

throwing "NoSuchElementException" is a strictly optional operation in an iterator (the javadoc state "NoSuchElementException - if the iteration has no more elements". This iteration always has more elements.

Spotbugs should not report an error here.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions