2

Possible Duplicate:
What is the easiest alternative to a generic array in Java?

I have the following code:

class B<X>
{
    public void create()
    {
        List<X> l1 = new ArrayList<X>(); //No ERROR

        X[] arrr = new X[10];   //ERROR
    }
}

I know that I cannot instantiate a Generic array due to type erasure. But why can I instantiate an instance of a generic List?

Community
  • 1
  • 1
Swaranga Sarma
  • 12,215
  • 19
  • 54
  • 87
  • possible duplicate of [What is the easiest alternative to a generic array in Java?](http://stackoverflow.com/questions/383888/what-is-the-easiest-alternative-to-a-generic-array-in-java) or (http://stackoverflow.com/questions/5626867/generic-class-to-array-of-generics-of-same-generic-type) – Lukas Eder May 23 '11 at 09:43
  • 1
    I think I understand the question. If `new ArrayList();` is essentially treated as `new ArrayList();` due to type erasure, why is `new X[10];` not handled like `new Object[10];`? - or vice-versa, if Java can't handle the array, how can it handle the list? – Alan Escreet May 23 '11 at 09:54
  • @Alan, Thank you. That is what I was asking. – Swaranga Sarma May 23 '11 at 10:01
  • @Lukas Eder...I completely disagree that it is a duplicate question. I am asking **why** can we create a Generic List instance but not a generic array instance. – Swaranga Sarma Jun 11 '11 at 10:10

2 Answers2

5

The reason is that generics are implemented using type erasure:

No type X is known at runtime. That means that you can't instantiate an array of that (unknown type).

But since you don't need (and in fact can't use) the type information for creating a parameterized type at runtime (again: type erasure), creating an ArrayList<X> is not a problem.

Note that internally an ArrayList always uses an Object[] for actual storage, no matter what the type argument is.

Joachim Sauer
  • 278,207
  • 54
  • 523
  • 586
0

Angelika Langer provides excellent documentation on Java generics. This link answers your question about the difference between Lists (and other generic types) and arrays and why you cannot instantiate arrays in this way:

http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html#FAQ104

In short: Because arrays are covariant, it is not type safe to instantiate an array of a parameterized type.

Alan Escreet
  • 3,349
  • 2
  • 20
  • 17