如何在 Java 中用全零初始化 ArrayList? [英] How can I initialize an ArrayList with all zeroes in Java?

查看:28
本文介绍了如何在 Java 中用全零初始化 ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来 arraylist 没有完成它的预调整工作:

It looks like arraylist is not doing its job for presizing:

// presizing 

ArrayList<Integer> list = new ArrayList<Integer>(60);

之后当我尝试访问它时:

Afterwards when I try to access it:

list.get(5) 

它不会返回 0,而是抛出 IndexOutOfBoundsException: Index 5 out of bounds for length 0.

Instead of returning 0 it throws IndexOutOfBoundsException: Index 5 out of bounds for length 0.

有没有办法像 C++ 那样将所有元素初始化为 0 的精确大小?

Is there a way to initialize all elements to 0 of an exact size like what C++ does?

推荐答案

传递给构造函数的整数表示它的初始容量,即在需要调整其大小之前它可以容纳的元素数内部数组(与列表中的初始元素数无关).

The integer passed to the constructor represents its initial capacity, i.e., the number of elements it can hold before it needs to resize its internal array (and has nothing to do with the initial number of elements in the list).

要使用 60 个零初始化列表,您可以:

To initialize an list with 60 zeros you do:

List<Integer> list = new ArrayList<Integer>(Collections.nCopies(60, 0));

<小时>

如果您想创建一个包含 60 个不同对象的列表,您可以使用带有 Supplier 的 Stream API,如下所示:


If you want to create a list with 60 different objects, you could use the Stream API with a Supplier as follows:

List<Person> persons = Stream.generate(Person::new)
                             .limit(60)
                             .collect(Collectors.toList());

这篇关于如何在 Java 中用全零初始化 ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆