通过零大小的数组,节省分配? [英] Pass zero-sized array, save allocation?
问题描述
在通过的良好接地Java开发,最后一行:
Update[] updates = lu.toArray(new Update[0]);
包含的说明:传递零大小的数组,节省分配
List<Update> lu = new ArrayList<Update>();
String text = "";
final Update.Builder ub = new Update.Builder();
final Author a = new Author("Tallulah");
for (int i=0; i<256; i++) {
text = text + "X";
long now = System.currentTimeMillis();
lu.add(ub.author(a).updateText(text).createTime(now).build());
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
}
Collections.shuffle(lu);
Update[] updates = lu.toArray(new Update[0]);
什么分配是心动,到底是什么?
What allocation is this saving, exactly?
有关的列表#的toArray(T []一)提到:
如果列表中的指定数组能容纳,它返回此处。
否则,一个新的数组分配与运行时类型的
指定数组并将此列表的大小。
If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.
这是我记得:如果你传递给的toArray数组(T []一)
不适合在列表中的一切,一个新的数组分配。说白了,有256个元素在列表中,这不适合于大小为0的数组,因此一个新的数组必须在方法内部分配的,对吧?
Which is what I remembered: if the array you pass to toArray(T[] a)
can't fit everything in the list, a new array is allocated. Plainly, there are 256 elements in the list, which cannot fit in an array of size 0, therefore a new array must be allocated inside the method, right?
那么,该说明不正确的?还是有别的什么意思?
So is that note incorrect? Or is there something else it means?
推荐答案
去关上这个问题@Andreas评论,我觉得它的是的一个错字,而应该说:
Going off of @Andreas comment on the question, I think it is a typo, and should say:
传递零大小的数组,安全分配。
Pass zero-sized array, safe allocation.
因为如果你没有传递给方法,你最终会调用的#列出的toArray()无参数超载!
Because if you passed nothing to the method, you'll end up calling the List#toArray() no-argument overload!
这将返回一个对象[]
(尽管它会包含什么,但更新
实例),并需要改变在更新
变量的类型,所以最后一行将变成:
This would return an Object[]
(though it would contain nothing but Update
instances) and would require changing the type of the updates
variable, so the last line would become:
Object[] updates = lu.toArray();
然后每次要遍历并使用数组中的元素时,你必须将它们转换成更新
。
供应数组调用的列表#的toArray(T []一)的方法,该方法返回一个&LT; T&GT; T []
。该数组物化知道它是更新
实例的数组。
Supplying the array calls the List#toArray(T[] a) method, which returns a <T> T[]
. This array is reified to know it is an array of Update
instances.
所以,提供更新的结果在更新[]从通话的toArray,而不是一个Object []回来一个空数组。这是一个更加类型 - 安全配置! 词救的说明必须是一个错字!的
So supplying an empty array of Updates results in an Update[] coming back from the toArray call, not an Object[]. This is a much more type-safe allocation! The word "save" in the note must be a typo!
...这消耗了太多的心力。将张贴链接到这本书的论坛,使他们能够改正。
...this consumed way too much mental effort. Will post link to this in the book's forums so they can correct it.
这篇关于通过零大小的数组,节省分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!