将包含数据的数组传递给List的toArray方法

Ami*_*adi 0 java list toarray

我有一些像这样的代码:

    String[] colors = {"black", "blue", "yellow", "red", "pink", "green", "cyan"};
    String[] alphabets = {"A", "B", "C", "D", "E", "F", "G", "H", "I"};
    LinkedList<String> links = new LinkedList<>(Arrays.asList(colors));
    System.out.println(links);
    colors = links.toArray(alphabets);
    System.out.println(Arrays.asList(colors));
Run Code Online (Sandbox Code Playgroud)

它的输出是:

[black, blue, yellow, red, pink, green, cyan]
[black, blue, yellow, red, pink, green, cyan, null, I]
Run Code Online (Sandbox Code Playgroud)

第二个输出行中的null是什么?为什么?

Ous*_* D. 5

当您对方法的特定行为有疑问时,最好的答案来源是检查文档.

java doc说明:

toArray(T [] a)

如果列表适合指定的数组,并且空间足够(即,数组的元素多于列表),则紧跟在列表末尾的数组中的元素将设置为null.(仅当调用者知道列表不包含任何null元素时,这在确定列表长度时很有用.)