Take the 2-minute tour ×

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)

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.

share|improve this question
well, in this case it doesn't, because that code won't compile: you can't create a generic array, and the parameterization of the class doesn't match the parameterization of its variables –  kdgregory Jun 10 '09 at 11:50
in fact, in this code there is no generic array being created at all... I don't see any "new" there :--) –  Carlos Heuberger Jun 10 '09 at 13:10
T implicity extends Object, so even during compilation T is just an Object with a few compile time checks. –  Peter Lawrey Jul 22 '10 at 22:25
add comment

2 Answers

up vote 8 down vote accepted

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.
share|improve this answer
I'm curious to know why I'm been downvoted. –  akappa Jun 10 '09 at 12:00
I am often mystified as to why some things are downvoted. +1 from me, as your answer is accurate and useful. –  Eddie Jun 10 '09 at 13:14
point 2 is wrong: arrays CAN be generic; you can not CREATE a generic array. See the code of the nested class Arrays.ArrayList... The following should compile (<br> should be a newline): <br> public class Test<T> { <br> private T[] list; <br> public Test(T[] aList) { <br> list = aList; <br> } <br> } –  Carlos Heuberger Jun 10 '09 at 13:17
Carlos, you're right. I edit my answer to reflect that –  akappa Jun 10 '09 at 14:21
add comment

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.

share|improve this answer
thanks code is just fr example.i just wanted to know whether its case fr userdefined too. –  Maddy.Shik Jun 10 '09 at 13:09
add comment

Your Answer


