Search code examples
javagenericscompilationtype-erasure

Does java implement type erasure in user defined generic classes too?


Suppose I have a class and I want to use it somewhere as a generic type:

class MyList<T>
{
    T[] list=T[10];

    public void add(T element)
    { 
        list[0]=element;
    }
}

After compilation, does it remove its type information like it is the case for generic collections?

I don't need to use this code anywhere, so please don't concentrate upon finding mistakes. I just wanna ask a general question through this code that after compilation will list instance variable be of type Object class.


Solution

  • Yes, of couse.

    Also note that:

    1. The type parameter of the class must match the generic type in its body
    2. You can't create a generic array, but you can declare it. The rationale behind that is that allowing construction of generic arrays would make java not type-safe anymore. Use an arraylist instead.