Unchecked assignment: 'anonymous java.util.Iterator' to 'java.util.Iterator<java.lang.Integer>'

I have a class like this

public class Symbol implements Iterable<Integer> {
    private int n = 123;

    public Iterator<Integer> iterator() {
        return new Iterator() {

            int counter = 0;

            @Override
            public boolean hasNext() {return counter < n;}

            @Override
            public Integer next() {return counter++;}

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

I get the following warning

 Unchecked assignment: 'anonymous java.util.Iterator' to 'java.util.Iterator<java.lang.Integer>'

Now I could just ignore the warning or fill an arraylist with a for loop and return the iterator of the list but I would like to do it lazy and I would like to do it right i.e. no warnings.

Jon Skeet
people
quotationmark

All you've got to do is change your anonymous class to use Iterator<Integer> instead of the raw type:

return new Iterator<Integer>() {
    // Code here as before
};

Imagine it had been written like this:

public Iterator<Integer> iterator() {
    Iterator iterator = new Iterator() { ... };
    return iterator;
}

At that point the problem is clear, right? You're using a value of the raw type Iterator to return from a method of type Iterator<Integer>. Well it's exactly the same without the local variable. With the suggested change, it's equivalent to the clearly-reasonable:

public Iterator<Integer> iterator() {
    Iterator<Integer> iterator = new Iterator<Integer>() { ... };
    return iterator;
}

people

See more on this question at Stackoverflow