-1

I want to create an array like this:

public class Population<T> {
    T[] a = new T[10];
}

However, the complier throws me this error:

Type parameter 'T' cannot be instantiated directly

Why does this happen, and what can I do to overcome this issue?

OriFl
  • 47
  • 6

1 Answers1

1

You can't do this directly, as the compiler has mentioned. Giving an answer that fits your case is not straightforward since there are no implementation details.

One possibility is to inject an array/list/collection via a constructor.

public class Population<T> {
    private final List<T> members; 
    public Population(List<T> members) {
        this.members = members;
    }
}

and then use becomes

List<Animal> animals = new ArrayList<Animal>();
Population<Animal> population = new Population(animals);
William Burnham
  • 4,234
  • 1
  • 13
  • 28