views:

277

answers:

2

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.

+7  A: 

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.
akappa
I'm curious to know why I'm been downvoted.
akappa
I am often mystified as to why some things are downvoted. +1 from me, as your answer is accurate and useful.
Eddie
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
Carlos, you're right.I edit my answer to reflect that
akappa
+4  A: 

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.

cletus
thanks code is just fr example.i just wanted to know whether its case fr userdefined too.
Maddy.Shik