Java Generics Error
generics, java
Solution
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):
@SuppressWarnings("unchecked")
public T[] createArray(Class<T> klass, int size) {
return (T[]) Array.newInstance(klass, size);
}
For example, in your case:
HashTable<Integer> t = new HashTable<Integer>();
Integer[] intArray = t.createArray(Integer.class, 4);
intArray[0] = 1; intArray[1] = 2;
intArray[2] = 3; intArray[3] = 4;
System.out.println(Arrays.toString(intArray));
> [1, 2, 3, 4]
Problem
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.