3

I have a class where I need the constructor to initialize variable array. I researched on the internet and also stack overflow but now I am stuck on how to call the method. For example how could I call method1 in my example?

public class SomeClass<T>{

   public T[] array;

   //Constructor
   public SomeClass()
   {
        Method1(T, 5); //?  error
        Method1(5); //?   error
        Method1(new T().GetType(), 5); //? error
        // HOW CAN I CALL THAT METHOD?

        array = (T[])(new Object[5]); // this gives an error too
   }

   private void Method1(Class<T> type, int size)
   {
       array = (T[])Array.newInstance(type, size);
   }
}
Cœur
  • 32,421
  • 21
  • 173
  • 232
Tono Nam
  • 29,637
  • 73
  • 252
  • 421

2 Answers2

5

Try this:

class SomeClass<T> {

    private T[] array;

    @SuppressWarnings("unchecked")
    public SomeClass(Class<T> klass, int size) {
        array = (T[]) Array.newInstance(klass, size);
    }

}

And to instantiate it:

SomeClass<Integer> example = new SomeClass<Integer>(Integer.class, 10);

Be aware that the array instantiated is an object array, and all its elements will be null until you explicitly assign them.

Óscar López
  • 215,818
  • 33
  • 288
  • 367
3

You would need to pass the Class object representing T into the SomeClass constructor:

public SomeClass(Class<T> clazz)
{
   array = Method1(clazz, 5);
}

This is necessary because of Type Erasure, which means T will have no meaning at runtime (Array.newInstance takes a Class object representing the array's element type for the same reason).

Paul Bellora
  • 51,514
  • 17
  • 127
  • 176