Can we convert a Java list to array?

JavaObject Oriented ProgrammingProgramming

<p>The List provides two methods to convert a List into Array.</p><h2>1. Use toArray() method without parameter.</h2><pre class="result notranslate">Object[] toArray()</pre><h3>Returns</h3><p>An array containing all of the elements in this list in proper sequence.</p><h2>2. Use toArray() with array.</h2><pre class="result notranslate">&lt;T&gt; T[] toArray(T[] a)</pre><h3>Parameters</h3><ul class="list"><li><p><strong>a&nbsp;</strong> &minus; The array into which the elements of this list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.</p></li></ul><h3>Returns</h3><p>An array containing the elements of this list.</p><h3>Throws</h3><ul class="list"><li><p><strong>ArrayStoreException</strong> &minus; If the runtime type of the specified array is not a supertype of the runtime type of every element in this list.</p></li><li><p><strong>NullPointerException&nbsp;</strong>&minus; If the specified array is null.</p></li></ul><h2>Example</h2><p>Following is the example showing the usage of toArray() methods &minus;</p><pre class="demo-code notranslate language-java" data-lang="java">package com.tutorialspoint; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CollectionsDemo { &nbsp; &nbsp;public static void main(String[] args) { &nbsp; &nbsp; &nbsp; List&lt;String&gt; list = new ArrayList&lt;&gt;(Arrays.asList(&quot;A&quot;,&quot;B&quot;,&quot;C&quot;, &quot;D&quot;)); &nbsp; &nbsp; &nbsp; System.out.println(&quot;List: &quot; + list); &nbsp; &nbsp; &nbsp; Object[] items = list.toArray(); &nbsp; &nbsp; &nbsp; for (Object object : items) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.print(object + &quot; &quot;); &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; System.out.println(); &nbsp; &nbsp; &nbsp; String[] characters = list.toArray(new String[0]); &nbsp; &nbsp; &nbsp; for (String string : characters) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.print(string + &quot; &quot;); &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;} }</pre><h2>Output</h2><p>This will produce the following result &minus;</p><pre class="result notranslate">List: [A, B, C, D] A B C D A B C D</pre>
Updated on 09-May-2022 11:57:35