Why is this compiling? Erase Type

Why the next compiler? I warn that

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

But I do not understand why getTestIntegers() not common. I would expect List<String> tester = Test.getTest().getTestIntegers() generate a compilation 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); } } } 
+6
source share
1 answer

As already stated, getTest returns a raw type. The correct implementation of the method will look like this:

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

Please note that you need to specify a common parameter for static methods - this can be anything, since it is not the same T as in the class signature (but it is usually customary to use the same name if it is used in the same place )

Then it depends on whether the compiler can infer the correct type, sometimes it may need your "help", for example

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

(I have not tried if necessary there, but how it looks)

+2
source

Source: https://habr.com/ru/post/1012580/


All Articles