title: Java: how to implement `toArray` for `Collection`
body: <p>Right now, I have:</p>
  
  <pre><code>    public &lt;T&gt; T[] toArray(T[] old) {
          T[] arr = Arrays.copyOf(old, old.length + size());
          int i = old.length;
          for(E obj : this) {
              arr[i] = old.getClass().getComponentType().cast(obj);
              ++i;
          }
          return arr;
      }
  </code></pre>
  
  <p>(Note that this does not follow the contract as it was pointed out by axtavt.)</p>
  
  <p>where I get this warning:</p>
  
  <pre><code>Type safety: Unchecked cast from capture#2-of ? to T
  </code></pre>
  
  <p>Is this still the best / most straightforward way to implement it? Can I somehow code it in a way without that warning? How would I implement it otherwise?</p>
  
  <hr>
  
  <p>Edit: My current solution. First, I really wanted to not have such a warning in <code>toArray</code> itself. Therefore, I coded these little helper functions (<a href="https://stackoverflow.com/questions/4011289/java-what-about-my-classof-and-newarray">read here</a> for a further discussion about these):</p>
  
  <pre><code>@SuppressWarnings("unchecked") static &lt;T&gt; Class&lt;? extends T&gt; classOf(T obj) {
      return (Class&lt;? extends T&gt;) obj.getClass();
  }
  
  @SuppressWarnings("unchecked") static &lt;T&gt; Class&lt;? extends T&gt; classOf(T[] array) {
      return (Class&lt;? extends T&gt;) array.getClass().getComponentType();
  }
  
  @SuppressWarnings("unchecked") static &lt;T&gt; T[] newArray(Class&lt;T&gt; clazz, int size) {
      return (T[]) Array.newInstance(clazz, size);
  }   
  </code></pre>
  
  <p>Now, my <code>toArray</code> implementation looks like:</p>
  
  <pre><code>    public &lt;T&gt; T[] toArray(T[] array) { 
          int size = size();
          if (array.length &lt; size) { 
              array = newArray(classOf(array), size);
          } else if (array.length &gt; size) {
              array[size] = null;
          }
  
          int i = 0;
          for (E e : this) {
              array[i] = classOf(array).cast(e);
              i++;
          }
          return array;
      } 
  </code></pre>