w3resource

Java ArrayList.toArray(T[] a)() Method

public <T> T[] toArray(T[] a)

The toArray() method is used to get an array which contains all the elements in ArrayList object in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
If the list 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 list.

Package: java.util

Java Platform: Java SE 8

Syntax:

toArray(T[] a)

Type Parameters: T - the runtime type of the array to contain the collection

Parameters:

Name Description
a The array into which the elements of the list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.

Return Value:
An array containing the elements of the list

Throws:

  • ArrayStoreException - if the runtime type of the specified array is not a supertype of the runtime type of every element in this list
  • NullPointerException - if the specified array is null

Pictorial presentation of ArrayList.toArray(T[] a) Method

Java ArrayList.toArray(T[] a) Method

Example: ArrayList.toArray(T[] a) Method

The following example shows the usage of java.util.Arraylist.toArray(T[] a)() method method.

import java.util.*;

public class test {
   public static void main(String[] args) {
      
    // create an empty array list with an initial capacity
    ArrayList<String> color_list = new ArrayList<String>(5);

    // use add() method to add values in the list
    color_list.add("White");
    color_list.add("Black");
    color_list.add("Red");
    color_list.add("White");
	color_list.add("Yellow");
	
    System.out.println("Size of the color_list: " + color_list.size());

    // Print the colors in the list
    for (String value : color_list){
      System.out.println("Color = " + value);
    }  
   // Create an array from the ArrayList
    String color_list2[] = new String[color_list.size()];
    color_list2 = color_list.toArray(color_list2);
         
   // Display the contents of the array
    System.out.println("Printing elements of color_list2:"); 
    for (String color : color_list2) {
      System.out.println("Color = " + color);
    }
  }
}
   

Output:

F:\java>javac test.java
F:\java>java test
Size of the color_list: 5
Color = White
Color = Black
Color = Red
Color = White
Color = Yellow
Printing elements of color_list2:
Color = White
Color = Black
Color = Red
Color = White
Color = Yellow

Java Code Editor:

Previous:toArray Method
Next:get Method



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-tutorial/arraylist/arraylist_toarray.php