6

Why does the following compile? I get a warning telling me that

getTest() returns a raw type so getTestIntegers() is erased

But I don't understand why, getTestIntegers() is not generic. I would have expected List<String> tester = Test.getTest().getTestIntegers() to produce a compile error

public class Scratchpad {

    public static void main(String[] args) {
        new Scratchpad().run();
    }

    private void run() {
        List<String> tester = Test.getTest().getTestIntegers();
    }

    private static class Test<T> {

        public static Test getTest() {
            return new Test();
        }

        public List<Integer> getTestIntegers() {
            return Collections.singletonList(1);
        }
    }
}
Tom Reay
  • 153
  • 2
  • 9
  • 2
    As the warning says, the method `getTest` returns the raw type `Test`. It shouldn't do that; you should add a type parameter to that method. When you use raw types, the compiler goes into backward compatibility mode and things don't work like you expect. See: [What is a raw type and why shouldn't we use it?](http://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) – Jesper Nov 23 '16 at 09:53
  • Thanks for the link, section "A raw type is the erasure of that type" deals with it and it is clearly in the JLS. But what I don't get is why? What is the reasoning for needing to erase `getTestIntegers()`? – Tom Reay Nov 23 '16 at 10:08

1 Answers1

2

As already was pointed out, getTest returns a raw type. A correct implementation of the method would look like this:

public static <T> Test<T> getTest() {
    return new Test<>();
} 

Note that you need to specify a generic parameter for static methods - it could be anything, as it is not the same T as in the class signature (but it is quite usual to use the same name, if it's used in the same place).

Then it depends if the compiler can infer the right type, sometimes it might need your "help", e.g.

List<String> tester = Test.<String>getTest().getTestIntegers();

(I didn't try out if this is necessary there, but that's how it looks)

Landei
  • 54,104
  • 13
  • 100
  • 195