title: How to create generic array?
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/529085/java-how-to-generic-array-creation">Java how to: Generic Array creation</a>  </p>
  </blockquote>
  
  
  
  <p>How to create an array of type <code>T[]</code> in Java? I can't use <code>Arrays.newInstance()</code> since I have no objects of <code>Class&lt;T&gt;</code>. Is there a generic version of <code>newInstance</code> somewhere?</p>
  
  <p>My method prototype follows:</p>
  
  <pre><code>public &lt;T&gt; T[][] distribute(T ... balls) {
     T[][] answer = ????
  
     // filling answer with data
  
     return answer;
  
  }
  </code></pre>
  
  <p><strong>UPDATE</strong></p>
  
  <p>Sorry in example above I can take class from <code>balls</code>. But suppose I have no such a variable.</p>
  
  <pre><code>public &lt;T&gt; T[][] distribute() {
     T[][] answer = ????
  
     // filling answer with data
  
     return answer;
  
  }
  </code></pre>
  
  <p>or </p>
  
  <pre><code>class&lt;T&gt; {
     public T[][] distribute() {
  
        T[][] answer = ????
  
        // filling answer with data
  
        return answer;
  
     }
  }
  </code></pre>
  
  <p><strong>UPDATE2</strong></p>
  
  <p>This example also does not work:</p>
  
  <pre><code>public abstract class GenericArray&lt;T&gt; {
  
  abstract public T create();
  
  public T[] gen1() {
      T[] ans = (T[]) new Object[3];
      ans[0] = create();
      ans[1] = create();
      ans[2] = create();
      return ans;
  }
  
  public Integer[] gen2() {
      Integer[] ans = new Integer[3];
      ans[0] = new Integer(0);
      ans[1] = new Integer(0);
      ans[2] = new Integer(0);
      return ans;
  }
  
  public static void main(String[] args) {
  
      GenericArray&lt;Integer&gt; a = new GenericArray&lt;Integer&gt;() {
  
          @Override
          public Integer create() {
              return new Integer(0);
          }
      };
  
      Integer[] b = a.gen2();
      Integer[] c = a.gen1(); // this causes ClassCastException
  
      System.out.println("done");
  
  }
  
  }
  </code></pre>