title: Returning an Array of a Generic Type in Java
body: <p>I have a class mapper that is supposed to apply any object that implements the Function interface to an array of type D, and return an array of type R.</p>
  
  <p>The problem is that Java does not let me use "new R[]," and so far I've struggled to figure out a way to create an R array from scratch. I currently am attempting to use the Array.newInstance method, but can't find a way to store the class type of R in a Class variable.</p>
  
  <pre><code>public class Mapper {
  
  
  /**
   * applies passed function to each object of type D in array
   * @param function
   * @param array
   * @return array of type r and length array.length
   */
  
  public static &lt;R, D&gt; R[] map(Function&lt;R, D&gt; function, D[] array)  {
  
      ArrayList&lt;R&gt; list = new ArrayList&lt;R&gt;();
  
      //apply function to each variable
      //add rs into object array
      for( int i = 0; i &lt; array.length; i++ ) {
  
          R r = function.apply( array[i] );
          list.add( r );
  
      }
  
  
  
      Class&lt;R&gt; clazz = list.get(0).getClass();
  
      return (R[])Array.newInstance(clazz, list.size()); 
  
  }
  
  }
  </code></pre>
  
  <p>What can I do properly attain a class value at runtime for the generic type R, or otherwise return the objects in ArrayList as an R[]?</p>