<p>In the Java collections framework, the Collection interface declares the following method:</p>
<blockquote>
<p><a href="http://java.sun.com/javase/6/docs/api/java/util/Collection.html#toArray(T%5B%5D)" rel="noreferrer"><code>&lt;T&gt; T[] toArray(T[] a)</code></a></p>
<p>Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection.</p>
</blockquote>
<p>If you wanted to implement this method, how would you create an array of the type of <strong>a</strong>, known only at runtime?</p>

[{'answer_id': 77426, 'author': 'Arno', 'author_id': 13685, 'author_profile': 'https://Stackoverflow.com/users/13685', 'pm_score': 2, 'selected': False, 'text': '<pre><code>Array.newInstance(Class componentType, int length)\n</code></pre>\n'}, {'answer_id': 77429, 'author': 'SCdF', 'author_id': 1666, 'author_profile': 'https://Stackoverflow.com/users/1666', 'pm_score': 4, 'selected': False, 'text': '<p>By looking at how ArrayList does it:</p>\n\n<pre><code>public &lt;T&gt; T[] toArray(T[] a) {\n    if (a.length &lt; size)\n        a = (T[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);\n    System.arraycopy(elementData, 0, a, 0, size);\n    if (a.length &gt; size)\n        a[size] = null;\n    return a;\n}\n</code></pre>\n'}, {'answer_id': 77474, 'author': 'user9116', 'author_id': 9116, 'author_profile': 'https://Stackoverflow.com/users/9116', 'pm_score': 6, 'selected': True, 'text': '<p>Use the static method</p>\n\n<pre><code>java.lang.reflect.Array.newInstance(Class&lt;?&gt; componentType, int length)\n</code></pre>\n\n<p>A tutorial on its use can be found here:\n<a href="http://java.sun.com/docs/books/tutorial/reflect/special/arrayInstance.html" rel="noreferrer">http://java.sun.com/docs/books/tutorial/reflect/special/arrayInstance.html</a></p>\n'}, {'answer_id': 77481, 'author': 'Christian P.', 'author_id': 9479, 'author_profile': 'https://Stackoverflow.com/users/9479', 'pm_score': -1, 'selected': False, 'text': "<p>To create a new array of a generic type (which is only known at runtime), you have to create an array of Objects and simply cast it to the generic type and then use it as such. This is a limitation of the generics implementation of Java (erasure).</p>\n\n<pre><code>T[] newArray = (T[]) new Object[X]; // where X is the number of elements you want.\n</code></pre>\n\n<p>The function then takes the array given (a) and uses it (checking it's size beforehand) or creates a new one.</p>\n"}]
['https://Stackoverflow.com/questions/77387', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13979/']