1

I would like to implement a template which contains an array of the template Type. Is there a way to do something similar to what I have outlined in my sample code? The problem is in the line where this.foo is assigned a new array of the template type.

class Classname<T>
{
  T[] foo
  Classname()
  {
    this.foo=new T[128];
  }
}
niklasfi
  • 12,699
  • 7
  • 35
  • 51

2 Answers2

3

This doesn't work, and here is a good answer that explains why. But, practically spoken, an Arraylist is a good replacement, because it basically wraps an array in a list object.

Edit

This question is even closer to your problem

Community
  • 1
  • 1
Andreas Dolk
  • 108,221
  • 16
  • 168
  • 253
0

This should work:

import java.lang.reflect.Array;
class Classname<T> {
  T[] foo;
  public Classname(Class<T> klass, int size) {
    this.foo = (T[]) Array.newInstance(klass, size);
  }
}

then you should be able to use it like this:

Classname<Double> c = new Classname<>(Double.class, 5);
Tombart
  • 26,066
  • 13
  • 112
  • 120