Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this compile? Type erasure [duplicate]

Tags:

java

generics

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);
        }
    }
}
like image 276
Tom Reay Avatar asked Nov 23 '16 09:11

Tom Reay


1 Answers

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)

like image 159
Landei Avatar answered Oct 24 '22 23:10

Landei