Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics Error [duplicate]

Tags:

java

generics

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.

like image 467
Pat Murray Avatar asked May 01 '12 13:05

Pat Murray


1 Answers

Yes, generic arrays cannot be created. The best workaround I know is to use collections instead:

private List<T> list;

.......

list = new ArrayList<T>();
like image 192
AlexR Avatar answered Sep 29 '22 02:09

AlexR