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

后端 未结 5 787
小蘑菇
小蘑菇 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:20

    Java 8 implementation (List initialized with 60 zeroes):

    List list = IntStream.of(new int[60])
                        .boxed()
                        .collect(Collectors.toList());
    
    • new int[N] - creates an array filled with zeroes & length N
    • boxed() - each element boxed to an Integer
    • collect(Collectors.toList()) - collects elements of stream

提交回复
热议问题