Why java raw type erase types of concretized members

57 Views Asked by At

Given below example:

import java.util.ArrayList;
import java.util.List;

public class MyTemplate<T> {

    T parameterizedObj;
    List<String> stringList;

    public static void main(String[] args) {
        String a = new MyTemplate().getStringList().get(0);
    }

    public List<String> getStringList() {
        if (stringList == null) {
            stringList = new ArrayList<>();
            stringList.add("Hello");
        }
        return stringList;
    }
}

Below error is given when compiling

/home/***/test/src/main/java/MyTemplate.java:10:56
java: incompatible types: java.lang.Object cannot be converted to java.lang.String

When MyTemplate is used as a raw type in this form new MyTemplate() in line 10.

I can understand the type of T parameterizedObj is erased to Object.

But I can't understand why List<String> stringList is erased to List. Since it has been concretized as List<String>. Why?

I read the document Raw Types and Type Erasure, but don't find an answer, I think they're talking about the use case of T parameterizedObj, not List<String> stringList

0

There are 0 best solutions below