The toArray() method of ArrayList is used to return an array containing all the elements in ArrayList in the correct order.
Declaring toArray() method
public Object[] toArray()
or
public <T> T[] toArray(T[] a)
Parameters: This method either accepts no parameters or it takes an array T[] as a parameter which is 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: The function returns an array containing all the elements in this list.
Exception: The first overload of this method throws no exceptions. However, the second overload throws the following exceptions:
- 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
Examples of Java ArrayList.toArray() method
Example 1
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
ArrayList<Integer> ArrLis
= new ArrayList<Integer>();
ArrLis.add( 32 );
ArrLis.add( 67 );
ArrLis.add( 98 );
ArrLis.add( 100 );
System.out.println( "ArrayList: " + ArrLis);
Object[] arr = ArrLis.toArray();
System.out.println( "Elements of ArrayList"
+ " as Array: "
+ Arrays.toString(arr));
}
}
|
OutputArrayList: [32, 67, 98, 100]
Elements of ArrayList as Array: [32, 67, 98, 100]
Example 2
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
ArrayList<Integer> ArrLis
= new ArrayList<Integer>();
ArrLis.add( 32 );
ArrLis.add( 67 );
ArrLis.add( 98 );
ArrLis.add( 100 );
System.out.println( " ArrayList: " + ArrLis);
Integer arr[] = new Integer[ArrLis.size()];
arr = ArrLis.toArray(arr);
System.out.println( " Elements of ArrayList "
+ "as Array: "
+ Arrays.toString(arr));
}
}
|
Output ArrayList: [32, 67, 98, 100]
Elements of ArrayList as Array: [32, 67, 98, 100]