1

I have a private member which is an array of type generics and in my constructor I have a parameter that is to set the size of this array. How could I set my private array to the size specified by the constructor parameter?

This is what I have:

private T[] hashTable;

public HashTable(int initSize){
    // set hashTable size here
}
Fabio
  • 21,516
  • 12
  • 49
  • 63
joe moe
  • 11
  • 5

1 Answers1

2

This solution requires an upcast from Object[].

public class HashTable<T> {
    private T[] hashTable;

    public HashTable(int initSize){ // set hashTable size here
        hashTable = (T[]) new Object[initSize];
    }
}
Kevin Bowersox
  • 88,138
  • 17
  • 142
  • 176