Library contents

Java List.toArray

Convert a list into an array of the required component type for an API that accepts arrays.

A simple example

List.toArray

  1. Start with List containing A and B
  2. Do this Convert to an array
  3. Result Array containing A and B
The representation changes while the order and values stay the same.

Syntax

Java syntax
names.toArray(String[]::new)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Send the badge roster to an older printer

A school stores its badge roster in a list, but the older printer driver accepts an array of names. The coordinator converts the roster before sending it to the printer in registration order.

From the programvar roster = List.of("Mira", "Sam")
ResultMira, Sam
Main.java
import java.util.List;

class Main {
    public static void main(String[] args) throws Exception {
        var roster = List.of("Mira", "Sam");
        String[] printJob = roster.toArray(String[]::new);
        System.out.println(String.join(", ", printJob));
    }
}
Output
Mira, Sam

The generator creates a String array with one slot for each name in the roster.

Advertisements

Correct a print job without editing the roster

A receptionist needs an uppercase name on one replacement badge. The temporary print array can be changed while the master list keeps the student's usual spelling.

From the programvar roster = List.of("Mira")
ResultMira
Main.java
import java.util.List;

class Main {
    public static void main(String[] args) throws Exception {
        var roster = List.of("Mira");
        String[] printJob = roster.toArray(String[]::new);
        printJob[0] = "MIRA";
        System.out.println(roster.get(0));
    }
}
Output
Mira

Replacing an element of the array does not replace the corresponding element of the list.

Load a lobby display

The gallery sends an ordered set of rooms to a display that accepts an array. Transfer the ordered entries to an array for the display. Which sequence will its positions contain?

GivenClay · Glass · Ink
Worked resultClay · Glass · Ink

What to watch for

The no-argument overload returns Object[]. Use the generator overload when the receiver needs a String[].

Documentation for List.toArray