Reputation: 13062
I am looking to reinvent the wheel a little and create my own generic array-backed list class in Java similar to ArrayList. Yes I know this is silly, but it is an academic pursuit. The problem is that you cannot instantiate an array of a generic type
public class MySuperCoolList<E> {
E[] array;
public MySuperCoolList<E> () {
array = new E[10]; // ERROR: cannot do this!
}
}
Surely there must be a solution to this problem because Java's ArrayList is doing the same thing. The question is, how? How can I instantiate an array of a generic type E
? And how is it done in ArrayList (if anyone knows)?
Upvotes: 0
Views: 1676
Reputation: 29646
public MySuperCoolList<E>(final Class<? extends E> type) {
array = (E[]) Arrays.newInstance(type, 10);
}
See Arrays.newInstance
. This is how Arrays.copyOf
works.
I've placed a PoC here.
int[] vals = (int[]) Array.newInstance(Integer.TYPE, 10);
vals[0] = 500;
System.out.println(vals);
System.out.println(vals.length);
System.out.println(Arrays.toString(vals));
As you can see, the output is as expected:
[I@fb53f6
10
[500, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Upvotes: 0
Reputation: 2421
In this case , you might want to use Array of Object Type , cause object type can accomodate everything and the code goes like,
public class MySuperCoolList<E> {
Object[] array;
public MySuperCoolList () {
array = new Object[10];
}
public E get(int index){
return (E) array[index];
}
public void put(int index,E val) {
array[index] = val;
}
}
Upvotes: 0
Reputation: 838106
And how is it done in ArrayList (if anyone knows)?
It's open source. Take a look at the source code for ArrayList
:
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer.
*/
private transient Object[] elementData;
Upvotes: 4