[英]Instantiating an array of Generic Class
How can I instantiate an array
of object of a Generic Class ? 如何实例化泛型类的对象array
?
I was implementing a Hash Table in Java
. 我正在用Java
实现哈希表 。
The Generic Class to be instantiated: 要实例化的泛型类 :
class GenericLinkedList<T> {
// Generic Class Codes Here
}
Hash Table Class: 哈希表类:
public class HashTable {
private GenericLinkedList[] table; // Generic Class Instantiation
private static final int SIZE = 50;
public HashTable() {
this.table = new GenericLinkedList[SIZE];
for(int i = 0; i < SIZE; i++)
this.table[i] = new GenericLinkedList();
}
}
You can't create an array of generic type. 您不能创建泛型类型的数组。 The following code is invalid: 以下代码无效:
List<String>[] listArray = new List<String>[10]; // Error
It would be better to use an Object[]
internally to store the elements, and let the method returning the elements do appropriate cast: 最好在内部使用Object[]
存储元素,并让返回元素的方法进行适当的转换:
public class HashTable<T> {
private Object[] table;
private static final int SIZE = 50;
public HashTable(){
this.table = new Object[SIZE];
for(int i = 0; i < SIZE; i++)
this.table[i] = new GenericLinkedList();
}
}
FYI, this is how the java.util.ArrayList
is implemented. 仅供参考,这就是java.util.ArrayList
的实现方式。
PS : Why your Hashtable
doesn't seem to have key-value mapping kind of thing? PS :为什么您的Hashtable
似乎没有键值映射之类的东西? This is more like a list. 这更像一个列表。
First of all, there is nothing wrong with the code you posted. 首先,您发布的代码没有错。 You probably wanted table
to be GenericLinkedList<T>[]
though. 您可能希望table
是GenericLinkedList<T>[]
。 The solution is simple, when creating the array, use either new GenericLinkedList[SIZE]
or new GenericLinkedList<?>[SIZE]
. 解决方案很简单,在创建数组时,请使用new GenericLinkedList[SIZE]
或new GenericLinkedList<?>[SIZE]
。
public class HashTable<T> {
private GenericLinkedList<T>[] table;
private static final int SIZE = 50;
public HashTable(){
this.table = new GenericLinkedList[SIZE];
for(int i = 0; i < SIZE; i++)
this.table[i] = new GenericLinkedList();
}
}
or 要么
public class HashTable<T> {
private GenericLinkedList<T>[] table;
private static final int SIZE = 50;
public HashTable(){
this.table = (GenericLinkedList<T>[])new GenericLinkedList<?>[SIZE];
for(int i = 0; i < SIZE; i++)
this.table[i] = new GenericLinkedList();
}
}
Why is not your HashTable generic itself? 为什么您的HashTable不通用? HashTable<T>
nicely solves your problem: HashTable<T>
很好地解决了您的问题:
this.table = new GenericLinkedList<T>[SIZE];
You might also use GenericLinkedList<?>
. 您也可以使用GenericLinkedList<?>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.