LinkedList.toArray(T[]) writes list members into a typed array and sets the first spare slot to null when the supplied array is larger.
Java LinkedList toArray(T[]): the null terminator boundary
The Java 8 program below compiles without external libraries; its output is checked against a real run.
Only one spare slot is reset
The supplied array starts with old values. Two receipt identifiers replace its first two positions, index two becomes null, and index three retains its old value. The API does not promise to clear the entire unused tail. A downstream reader that scans every slot can accidentally process stale data.
If the supplied array is too small, the method allocates another array with the supplied runtime component type. Always use the returned reference; assuming the original was filled is wrong in that case.
Null may also be a member
LinkedList permits null elements. The first null in a typed array is not a reliable length marker unless the application prohibits null members. Use the known list size or the returned array length according to the receiving API's contract. Null head ambiguity is the same policy problem at a different boundary.
Working program
import java.util.Arrays;
import java.util.LinkedList;
public class ReceiptArrayExport {
public static void main(String[] args) {
LinkedList<String> receipts = new LinkedList<>(Arrays.asList("R-21", "R-22"));
String[] reusable = {"old-0", "old-1", "old-2", "old-3"};
String[] exported = receipts.toArray(reusable);
System.out.println("same array=" + (exported == reusable));
System.out.println(Arrays.toString(exported));
}
}Output
same array=true
[R-21, R-22, null, old-3]Costs and boundaries
Copying n references into an array is O(n) time. A sufficiently large supplied array avoids allocating a new array, but retained element objects are still shared; the operation does not deep-copy them.
Common Mistakes
- Do not read the entire oversized array as fresh list data.
- Do not use null as a length marker while null list elements are legal.
- Do not discard the returned array when the input array may be too small.
Read next
Java LinkedList: operations, internals and failure cases, Java LinkedList null elements: an empty-head ambiguity, Java LinkedList clone: copied nodes, shared element objects.
