我有一些像这样的代码:
ps aux | grep sidekiq
,其输出为:
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));
第二个输出行中的null是什么?为什么?
答案 0 :(得分:5)
当您对方法的特定行为有疑问时,最好的答案来源是检查文档。
java doc声明:
<强> toArray(T[] a) 强>
如果列表适合指定的数组,并且有空余空间(即 数组中包含的元素多于列表中的元素 紧接在列表结尾之后设置为null。 (这是 仅在调用者知道时才用于确定列表的长度 该列表不包含任何null元素。)
答案 1 :(得分:3)
这就是LinkedList.toArray
的工作原理。基本上你要求将包含7个元素的列表包装到9个元素大小的数组中。
第7个元素是null
因为toArray
方法中的代码:
if (a.length > size)
a[size] = null;
,第8个元素从该数组的初始状态开始保持I
。