Question

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();
    }
}
Was it helpful?

Solution

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.

OTHER TIPS

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();
    }
}

Why is not your HashTable generic itself? HashTable<T> nicely solves your problem:

this.table = new GenericLinkedList<T>[SIZE];

You might also use GenericLinkedList<?>.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top