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?

4
  • possible duplicate of What is the easiest alternative to a generic array in Java? or (stackoverflow.com/questions/5626867/…) Commented May 23, 2011 at 9:43
  • 1
    I think I understand the question. If new ArrayList<X>(); is essentially treated as new ArrayList<Object>(); 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? Commented May 23, 2011 at 9:54
  • @Alan, Thank you. That is what I was asking. Commented May 23, 2011 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. Commented Jun 11, 2011 at 10:10

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.