What's the reason Java doesn't allow us to do
private T[] elements = new T[initialCapacity];
I could understand .NET didn't allow us to do that, as in .NET you have value types that at run-time can have different sizes, but in Java all kinds of T will be object references, thus having the same size (correct me if I'm wrong).
What is the reason?
I know I'm a little late to the party here, but I figured I might be able to help any future googlers since none of these answers fixed my issue. Ferdi265's answer helped immensely though.
I'm trying to create my own Linked list, so the following code is what worked for me:
In the toArray() method lies the way to create an array of a generic type for me:
It is because generics were added on to java after they made it, so its kinda clunky because the original makers of java thought that when making an array the type would be specified in the making of it. So that does not work with generics so you have to do E[] array=(E[]) new Object[15]; This compiles but it gives a warning.
The reason this is impossible is that Java implements its Generics purely on the compiler level, and there is only one class file generated for each class. This is called Type Erasure.
At runtime, the compiled class needs to handle all of its uses with the same bytecode. So,
new T[capacity]
would have absolutely no idea what type needs to be instantiated.There surely must be a good way around it (maybe using reflection), because it seems to me that that's exactly what
ArrayList.toArray(T[] a)
does. I quote:So one way around it would be to use this function i.e. create an
ArrayList
of the objects you want in the array, then usetoArray(T[] a)
to create the actual array. It wouldn't be speedy, but you didn't mention your requirements.So does anyone know how
toArray(T[] a)
is implemented?The answer was already given but if you already have an Instance of T then you can do this:
Hope, I could Help, Ferdi265
By failing to provide a decent solution, you just end up with something worse IMHO.
The common work around is as follows.
is replaced with (assuming T extends Object and not another class)
I prefer the first example, however more acedemic types seem to prefer the second, or just prefer not to thing about it.
Most of the examples of why you can't just use an Object[] equally apply to List or Collection (which are supported), so I see them as very poor arguments.
Note: this is one of the reasons the Collections library itself doesn't compile without warnings. If you this usecase cannot be supported without warnings, something is fundermentally broken with the generics model IMHO.