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
  • 23,183
  • 12
  • 55
  • 64
joe moe
  • 11
  • 1
  • 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
  • 93,289
  • 19
  • 159
  • 189