title: Java use generics to set the primitive type of an array later
body: <p>I am trying to write some simple numerical code in Java where one can choose between a float and double later. A simplified version of my class looks like the example below:</p>
  
  <pre><code>public class UniformGrid&lt;T&gt; {
  
      public T[] data;
  
      public UniformGrid(int arrayDim) {
  
          data = new T[arrayDim];
  
      }
  }
  </code></pre>
  
  <p>This didn't work I got a <code>generic array creation</code> error when trying to compile. Googling and reading some SO answers I learned about <code>java.lang.reflect.Array</code> and tried to use </p>
  
  <pre><code>    data = (T[]) Array.newInstance(T.class, arrayDim);
  </code></pre>
  
  <p>Which also didn't work, since T is (probably) a primitive type. My Java knowledge is quite rusty (especially when it comes to generics) and I would like to know why the new operator cannot be used with a generic array type. Also of course I am interested in how one would solve this problem in Java. </p>