如何初始化一个ArrayList与Java中的所有零? [英] How can I initialize an ArrayList with all zeroes in Java?

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

问题描述

看起来 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的确切大小,就像C ++一样?

It shows null instead of 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 不同的对象,您可以使用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());

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

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