Reputation: 115
How can I instantiate an array
of object of a Generic Class?
I was implementing a Hash Table in 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();
}
}
Upvotes: 0
Views: 264
Reputation: 122499
First of all, there is nothing wrong with the code you posted. You probably wanted table
to be GenericLinkedList<T>[]
though. The solution is simple, when creating the array, use either new GenericLinkedList[SIZE]
or 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();
}
}
Upvotes: 0
Reputation: 213351
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:
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.
P.S.: Why your Hashtable
doesn't seem to have key-value mapping kind of thing? This is more like a list.
Upvotes: 2
Reputation: 7376
Why is not your HashTable generic itself? HashTable<T>
nicely solves your problem:
this.table = new GenericLinkedList<T>[SIZE];
You might also use GenericLinkedList<?>
.
Upvotes: -1