Possible Duplicate:
Java how to: Generic Array creation
Error: Generic Array Creation
I am getting this error:
Cannot create a generic array of T
This is my code (error on line 6):
1 public class HashTable<T> {
2
3 private T[] array;
4
5 HashTable(int initSize) {
6 this.array = new T[initSize];
7 }
8 }
I am wondering why this error is appearing and the best solution to fix it. Thanks.
UPDATE:
I adjusted my code so that the array is taking in linked lists instead, but I am getting a new error.
Here is my error:
Cannot create a generic array of LinkedList<T>
Here is my code (error on line six):
1 public class HashTable<T> {
2
3 private LinkedList<T>[] array;
4
5 HashTable(int initSize) {
6 this.array = new LinkedList<T>[initSize];
7 }
8 }
Is this error for the exact same reason? I was just assuming I could create generic linked lists and just store them in the array.
Generic arrays can be created via reflection (although an unsafe cast is required), you just need to pass the class as a parameter (assuming that the following method is inside a class that defines a
<T>type parameter):For example, in your case: