How do you convert an ArrayList to an array in Java?

An ArrayList provides two toArray() methods to convert it into an array − one returns an Object[] array, and the other returns a typed array.

Method 1: toArray() (Returns Object[])

Object[] toArray()

Returns an array containing all elements in proper sequence. The returned array type is Object[], so casting is needed to use specific types.

Method 2: toArray(T[]) (Returns Typed Array)

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

Returns a typed array containing all elements. Pass an empty array of the desired type and Java allocates the correct size. This is the preferred approach as it avoids casting.

Example

The following example demonstrates both methods ?

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CollectionsDemo {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "D"));
        System.out.println("List: " + list);

        // Method 1: toArray() - returns Object[]
        Object[] items = list.toArray();
        System.out.print("Object[]: ");
        for (Object obj : items) {
            System.out.print(obj + " ");
        }
        System.out.println();

        // Method 2: toArray(T[]) - returns typed String[]
        String[] characters = list.toArray(new String[0]);
        System.out.print("String[]: ");
        for (String str : characters) {
            System.out.print(str + " ");
        }
    }
}

The output of the above code is ?

List: [A, B, C, D]
Object[]: A B C D
String[]: A B C D

Conclusion

Use toArray(new T[0]) for type-safe conversion from ArrayList to array. The no-argument toArray() returns Object[] which requires casting, so the typed version is preferred in most cases.

Updated on: 2026-03-14T19:46:38+05:30

744 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements