0

Searching this only found answers in C++, which I know plenty well already, but how do I do this in Java? I found answers that suggest I need to do the following:

class FixedArray<T> {

    public FixedArray(byte size) {
        array = new T[size];
    }

    private T[] array;
}

... but I get the error

Type parameter 'T' cannot be instantiated directly
Iron Attorney
  • 862
  • 1
  • 8
  • 19

1 Answers1

2

Actually T is not any data type but just a representative for Generics so you need to initialize a general Object[] array and cast it to Generic Type T,

Try this:

class FixedArray<T> {
public FixedArray(byte size) {
    array = (T[]) new Object[size];
}

private T[] array;
}

so for instance, you need to have an integer array it will be equivalent to:

Integer[] array = (Integer[]) new Object[size];
Mustahsan
  • 3,370
  • 1
  • 11
  • 27