0
import java.util.Iterator;

public class Main {
    public static class ShouldBeIterable<T> implements Iterable<Integer> {
        @Override
        public Iterator<Integer> iterator() {
            return null;
        }
    }

    public static void main(String[] args) {
        ShouldBeIterable it = new ShouldBeIterable();

        for (Integer i : it) {
            System.out.println("Bla");
        }
    }
}

The code above compiles with following error:

Error:(17, 26) java: incompatible types: java.lang.Object cannot be converted to java.lang.Integer

However, if I generify it with practically any type (even Object), the error disappears.

Why? How does it work? How can I solve this issue without using generics?

voismager
  • 433
  • 4
  • 19
  • While this is probably a small example and not your real use-case, one solution is to just remove `` from the `ShouldBeIterable` class and make it not generic. – nickb Jan 25 '19 at 18:03
  • Hm... providing a type for `T` (even if it's `Object`) makes the error go away. It seems that using raw types disables any sort of generic checking, even in superclasses. – Silvio Mayolo Jan 25 '19 at 18:04
  • 1
    [Relevant section of the JLS](https://docs.oracle.com/javase/specs/jls/se10/html/jls-4.html#jls-4.8). Note that Example 4.8-2 is almost verbatim the example in your question. – Silvio Mayolo Jan 25 '19 at 18:08

0 Answers0