[英]How do I make a generic list in Java?
I am looking to reinvent the wheel a little and create my own generic array-backed list class in Java similar to ArrayList. 我希望稍微改头换面,并用类似于ArrayList的Java创建自己的通用数组支持的列表类。 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. 当然,必须有解决此问题的方法,因为Java的ArrayList在做同样的事情。 The question is, how?
问题是,如何? How can I instantiate an array of a generic type
E
? 如何实例化通用类型
E
的数组? And how is it done in ArrayList (if anyone knows)? 以及如何在ArrayList中完成(如果有人知道)?
And how is it done in ArrayList (if anyone knows)?
以及如何在ArrayList中完成(如果有人知道)?
It's open source. 它是开源的。 Take a look at the source code for
ArrayList
: 看一下
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;
In this case , you might want to use Array of Object Type , cause object type can accomodate everything and the code goes like, 在这种情况下,您可能要使用Object Type的Array,因为object type可以容纳所有内容,并且代码如下所示,
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;
}
}
public MySuperCoolList<E>(final Class<? extends E> type) {
array = (E[]) Arrays.newInstance(type, 10);
}
See Arrays.newInstance
. 请参阅
Arrays.newInstance
。 This is how Arrays.copyOf
works. 这就是
Arrays.copyOf
工作方式。
I've placed a PoC here . 我已经在这里放置了PoC。
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.