Java ArrayList.toArray(): Converting Lists into Object & Typed Arrays

The ArrayList.toArray() method exports all elements of an ArrayList into a newly allocated Java array in exact index order (0 to size() - 1) in O(n) time.

Safe Snapshot Copy: The returned array is a completely independent buffer: modifying slots in the returned array never alters the original ArrayList. For working with native Java arrays and methods, see Java Arrays & Methods. To copy into another ArrayList instead of an array, use ArrayList.clone().

1. Syntax & All Three Overloaded Signatures 🔝

Declared in java.util.ArrayList<E> (implementing Collection.toArray):

 // 1. Returns a newly allocated Object[] array containing all elements in order
public Object[] toArray()

 // 2. Returns a typed T[] array containing all elements in order
public <T> T[] toArray(T[] a)

 // 3. Java 11+: Returns a typed T[] array using an array constructor reference (e.g., String[]::new)
public <T> T[] toArray(IntFunction<T[]> generator)
Overload Signature Return Type Behavior & Java Version
toArray() Object[] Returns a new Object[size()] array (cannot be cast to String[]!).
toArray(T[] a) T[] Copies into a if a.length >= size(), or allocates a new T[size()] via reflection.
toArray(IntFunction<T[]> g) T[] Java 11+: Calls g.apply(0) (e.g., String[]::new) and returns a new T[size()].

2. Basic Export to Object[] Using No-Arg toArray() 🔝

Calling languages.toArray() with no arguments returns an Object[] containing every element added via add() in exact sequence:

ArrayList<String> languages = new ArrayList<>(Arrays.asList("Java", "PHP", "HTML"));
System.out.println(languages);  // [Java, PHP, HTML]

Object[] my_array = languages.toArray();
System.out.println("Printing array elements:");
for (Object value : my_array) {
    System.out.println(value);
}

Terminal Output:

[Java, PHP, HTML]
Printing array elements:
Java
PHP
HTML

3. Exporting a Strongly Typed Array: Integer[] & String[] 🔝

To obtain a typed Integer[] or String[] without casting individual elements, pass a typed array witness (either pre-sized with marks.size(), an empty new Integer[0], or Java 11+ Integer[]::new):

ArrayList<Integer> marks = new ArrayList<>(Arrays.asList(54, 55, 56));
System.out.println("Marks list: " + marks);  // [54, 55, 56]

 // Approach A: Pre-sized array using marks.size()
Integer[] arr1 = marks.toArray(new Integer[marks.size()]);

 // Approach B: Empty array witness (preferred prior to Java 11)
Integer[] arr2 = marks.toArray(new Integer[0]);

 // Approach C: Java 11+ constructor reference
Integer[] arr3 = marks.toArray(Integer[]::new);
System.out.println("Typed Integer[]: " + Arrays.toString(arr3));

Terminal Output:

Marks list: [54, 55, 56]
Typed Integer[]: [54, 55, 56]

4. What Happens When the Passed Array Is Larger Than size()? 🔝

If you pass an array target whose length is strictly greater than list.size(), toArray(target) reuses target, writes the list elements into indices 0..size()-1, and writes a null terminator at index size() (leaving higher indices untouched):

ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "B"));
String[] target = {"X", "Y", "Z", "W"};  // length 4 > list.size() 2

String[] res = list.toArray(target);
 // Slot 0="A", Slot 1="B", Slot 2=null (terminator!), Slot 3="W" (unchanged)
System.out.println("Oversized target: " + Arrays.toString(res));

Terminal Output:

Oversized target: [A, B, null, W]

5. Exception Rules: ArrayStoreException & NullPointerException 🔝

If the runtime type of the passed array cannot hold every element in the list, toArray(T[] a) throws an ArrayStoreException. Passing null as the array argument throws a NullPointerException:

ArrayList<Object> mixed = new ArrayList<>(Arrays.asList("Java", 42));

try {
     // 42 is an Integer, which cannot be stored in a String[]!
    mixed.toArray(new String[0]);
} catch (ArrayStoreException ex) {
    System.out.println("Caught incompatible element: ArrayStoreException");
}

Terminal Output:

Caught incompatible element: ArrayStoreException

6. Comparison: new T[0] vs new T[size()] vs T[]::new 🔝

Which typed toArray() idiom should you use in modern Java?

Idiom JVM Performance Recommendation
list.toArray(String[]::new) Fastest (Java 11+) Cleanest modern syntax; zero reflection overhead.
list.toArray(new String[0]) Fastest (Java 8+) Avoids double-zeroing a pre-sized array before Arrays.copyOf.
list.toArray(new String[list.size()]) Slightly slower Classic pre-Java 6 style; allocates and zero-fills array twice.

7. Production Recipe: Converting ArrayList<Integer> to Primitive int[] 🔝

Because Java generics only support reference types, toArray() cannot return a primitive int[] or double[] directly. Use an indexed loop with list.get(i) (or list.stream().mapToInt(Integer::intValue).toArray()) to unbox into a primitive array:

public class PrimitiveIntArrayExport {
    public static int[] toPrimitiveIntArray(ArrayList<Integer> list) {
        int[] res = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            res[i] = list.get(i);  // Auto-unboxes Integer to primitive int
        }
        return res;
    }
    public static void main(String[] args) {
        ArrayList<Integer> scores = new ArrayList<>(Arrays.asList(88, 92, 95));
        int[] raw = toPrimitiveIntArray(scores);
        System.out.println("Primitive int[]: " + Arrays.toString(raw));
    }
}

Terminal Output:

Primitive int[]: [88, 92, 95]

8. Practical Recipe: Verifying Array & List Independence 🔝

Unlike Arrays.asList(arr) (which links the list to the array), ArrayList.toArray() always copies the references into a separate array so assignments to exported[0] never modify the list:

ArrayList<String> list = new ArrayList<>(Arrays.asList("Alpha", "Beta"));
String[] exported = list.toArray(new String[0]);
exported[0] = "MUTATED";
System.out.println("Array: " + Arrays.toString(exported) + " | List: " + list);

Terminal Output:

Array: [MUTATED, Beta] | List: [Alpha, Beta]

9. Common Developer Pitfalls & Traps 🔝

ClassCastException: (String[]) languages.toArray()

The no-argument languages.toArray() creates an Object[] at runtime—even on an ArrayList<String> (due to generic type erasure). Casting (String[]) languages.toArray() always throws a ClassCastException: class [Ljava.lang.Object; cannot be cast to class [Ljava.lang.String;! Always use languages.toArray(new String[0]) instead.

Printing an Array Directly with System.out.println(arr)

Unlike ArrayList, Java arrays do not override Object.toString(), so System.out.println(my_array) prints a hash like [Ljava.lang.Object;@15db9742. Wrap the array in Arrays.toString(my_array) or iterate with a loop.

10. Complete Compilable Java Program 🔝

Compile and run this verification class in any Java environment:

public class ArrayListToArrayFullDemo {
    public static void main(String[] args) {
        ArrayList<String> langs = new ArrayList<>(Arrays.asList("Java", "PHP", "HTML"));
        Object[] objArr = langs.toArray();
        String[] strArr = langs.toArray(new String[0]);
        if (objArr.length == 3 && strArr[1].equals("PHP")) {
            System.out.println("Check 1 Passed: Object[] and typed String[] lengths verified.");
        }
        strArr[0] = "Rust";
        if (langs.get(0).equals("Java")) {
            System.out.println("Check 2 Passed: Array mutation does not alter ArrayList.");
        }
        System.out.println("All ArrayList.toArray() verification checks passed!");
    }
}

Terminal Output:

Check 1 Passed: Object[] and typed String[] lengths verified.
Check 2 Passed: Array mutation does not alter ArrayList.
All ArrayList.toArray() verification checks passed!

11. Frequently Asked Questions (FAQ) 🔝

Why is list.toArray(new String[0]) faster than list.toArray(new String[list.size()])?

When you pass new String[list.size()], the JVM must allocate and zero-fill that array before calling toArray(), and then toArray() overwrites it with System.arraycopy(). When you pass new String[0], the JVM's intrinsic Arrays.copyOf() allocates and populates the exact array in a single step without redundant zero-filling.

Can I call toArray() on a subList()?

Yes! Calling list.subList(1, 4).toArray(new String[0]) exports only the elements in that range into a new array.

Does toArray() perform a deep copy of mutable objects?

No. Like ArrayList.clone(), toArray() copies object references into the new array.

How do I convert a Java array back into a mutable ArrayList?

Use new ArrayList<>(Arrays.asList(my_array)).

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer