How can I initialize an ArrayList with all zeroes in Java?

后端 未结 5 811
小蘑菇
小蘑菇 2020-11-27 10:37

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

// presizing 

ArrayList list = new ArrayList(60);
         


        
5条回答
  •  盖世英雄少女心
    2020-11-27 11:27

    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).

    To initialize an list with 60 zeros you do:

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

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

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

提交回复
热议问题