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);
}
}
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With