简体   繁体   中英

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.

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.

I'm not even sure that'll compile. It should at least offer a warning.

The problem here is that arrays are covariant. Generics are not. That means generics don't retain type information at runtime. Arrays do.

And yes that applies to all generic types, including user-defined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM