List ToArray Sized Array Contract

Convert a List with toArray: the no-arg form erases to Object[], new String[0] allocates the right type, and an oversized array keeps spare slots null.

JavaData Integrity

Code

snippet
import java.util.Arrays;
import java.util.List;

public class ToArrayContract {

    public static void main(String[] args) {
        List<String> names = List.of("ada", "lin", "raj");

        // 无参 toArray:类型擦除,只能得到 Object[]
        Object[] raw = names.toArray();
        System.out.println("raw is String[]: " + (raw instanceof String[]));

        // 零长度数组惯用法:toArray 按需分配并返回正确类型
        String[] sized = names.toArray(new String[0]);
        System.out.println("sized: " + Arrays.toString(sized));

        // 过大数组:不重新分配,紧跟列表末尾的元素被置为 null
        String[] over = names.toArray(new String[5]);
        System.out.println("over length: " + over.length);
        System.out.println("over[2]: " + over[2]);
        System.out.println("over tail: " + Arrays.toString(Arrays.copyOfRange(over, 3, 5)));
    }
}

How it works

The working surface is the class ToArrayContract and the function main — everything else is wiring.

Caveats

  • No external surface — every behavior comes from the standard library.

Putting it to use

Entry signature: public static void main(String[] args)

The file’s steps are announced right in the output: raw is String[]:, sized:, over length:.

The core lines of the flow

List<String> names = List.of("ada", "lin", "raj");
String[] sized = names.toArray(new String[0]);
String[] over = names.toArray(new String[5]);

Interactive Tools for This Topic

FAQ

What does List ToArray Sized Array Contract print when run?
Execute the whole file; each printed line is prefixed with a label like `raw is String[]:`, `sized:`, `over length:`.