Java ArrayList.toArray()

Learn to convert ArrayList to an array using toArray() method. The toArray() method returns an array that contains all elements from the list – in sequence (from first to last element in the list).

ArrayList<String> list = ...;

Object[] array = list.toArray();  //1

String[] array = list.toArray(new String[list.size()]);  //2

1. ArrayList.toArray() API

The toArray() is an overloaded method:

public Object[] toArray();

public <T> T[] toArray(T[] a);
  • The first method does not accept any argument and returns the Object[]. We must iterate the array to find the desired element and cast it to the desired type.
  • In second method, 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.

    After filling all array elements, if there is more space left in array then 'null' is populated in all those spare positions.

Seel Also: Java Stream toArray()

2. ArrayList toArray() Examples

2.1. Using toArray()

Java program to convert an ArrayList to Object[] and iterate through array content.

ArrayList<String> list = new ArrayList<>();
 
list.add("A");
list.add("B");
list.add("C");
list.add("D");
 
//Convert to object array
Object[] array = list.toArray();

//Iterate and convert to desired type
for(Object o : array) {
    String s = (String) o;  //This casting is required
    System.out.println(s);
}

Program output.

A
B
C
D

2.2. Using toArray(T[] a)

Java program to convert an ArrayList to String[].

ArrayList<String> list = new ArrayList<>(2);
 
list.add("A");
list.add("B");
list.add("C");
list.add("D");
 
String[] array = list.toArray(new String[list.size()]);

System.out.println(Arrays.toString(array));

Program output.

[A, B, C, D]

Happy Learning !!

Sourcecode on Github

Comments

Subscribe
Notify of
guest
2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode