加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 传递零大小的数组,保存分配?

发布时间:2020-12-15 03:08:40 所属栏目:Java 来源:网络整理
导读:在此代码示例中,来自第107页的第107页,最后一行: Update[] updates = lu.toArray(new Update[0]); 包含注释:传递零大小的数组,保存分配 ListUpdate lu = new ArrayListUpdate();String text = "";final Update.Builder ub = new Update.Builder();final Au
在此代码示例中,来自第107页的第107页,最后一行:
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]);

究竟是什么分配节省了?

List#toArray(T[] a)的javadoc提到:

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 [] a)的数组不能适合列表中的所有内容,则会分配一个新数组.显然,列表中有256个元素,不能放入大小为0的数组中,因此必须在方法内部分配一个新数组,对吧?

这个说明是不正确的?或者它意味着什么呢?

解决方法

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?

是.

您可以使用

private static final Update NO_UPDATES = { }

 lu.toArray(NO_UPDATES);

但是,如果您希望列表通常为0长度,这将只会有所帮助.

一般来说,我会采用与fge相同的方法

lu.toArray(new Update[lu.size()]);

在您的具体情况下,您事先知道尺寸,这样您就可以做到

Update[] updates = new Update[256];
String text = "";
final Update.Builder ub = new Update.Builder();
final Author a = new Author("Tallulah");

long now = System.currentTimeMillis();
for (int i=0; i<updates.length; i++) 
  updates[i] = ub.author(a).updateText(text += 'X').createTime(now++).build();

Collections.shuffle(Arrays.asList(updates));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读