Why doesn't Java allow creating a generic array?

Now, I've seen many similar questions of this or that before, and I understand the "due to erasure" answer. But I don't understand why erasure is preventing us from creating an array of generics.

As far as I understand; arrays are contiguous memory allocations containing primitives or object references. If I'm not mistaken, java arrays are a bit more than C / C ++ arrays with a little fancy dressing around them. Is it correct?

If so, why is erasure preventing the creation of an array like this for generic types? Are not all references the same size regardless of the class type? The class, of course, will be larger or smaller, but this should not affect the link. So don't we know exactly how big the array should be?

Or is it technically possible to do it, but another problem arises if we allow the creation of shared arrays?


To be clear: I understand what erase is and how it works. I understand how I can create an array given the above constraints. I do not want to do this.

I just want to understand why the type information is required when creating an array.

+3


source to share


2 answers


You are wrong. Arrays in Java contain type information encoded in them. The array itself is an object and type. You can do String[]

and call wait () and toString () on it and this type is different from type String

. There is more than one type of array, each type is different. You can call getClass()

on String[]

and it will return a different class than any other type of array.

So, if the type that it itself is erasing (which means "erasing"), there is no type to do T

or whatever.

Thus, you have to fake it with Object[]

, which will retain any type, but is not actually a specific type.



However, you can make the array type reflexively. Call

Array.newInstance( t.getClass(), <dim> );

      

and you can create a specific type of array if T

is the correct type.

0


source


Why not:

Object [] a = new Object[100];

      



That does not make a , you'd expect of a hypothetical "general" of the array? Each item can be a different type of object. You will need to qualify all element references, but each element can be anything, including null .

In this example, a symbol a refers to an object with a fixed size, and controls the array. The only thing that goes into the array is references to other objects.

0


source







All Articles