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

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

    The 60 you're passing is just the initial capacity for internal storage. It's a hint on how big you think it might be, yet of course it's not limited by that. If you need to preset values you'll have to set them yourself, e.g.:

    for (int i = 0; i < 60; i++) {
        list.add(0);
    }
    
    0 讨论(0)
  • 2020-11-27 11:20

    Java 8 implementation (List initialized with 60 zeroes):

    List<Integer> 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
    0 讨论(0)
  • 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<Integer> list = new ArrayList<Integer>(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<Person> persons = Stream.generate(Person::new)
                                 .limit(60)
                                 .collect(Collectors.toList());
    
    0 讨论(0)
  • 2020-11-27 11:29

    It's not like that. ArrayList just uses array as internal respentation. If you add more then 60 elements then underlaying array will be exapanded. How ever you can add as much elements to this array as much RAM you have.

    0 讨论(0)
  • 2020-11-27 11:33
    // apparently this is broken. Whoops for me!
    java.util.Collections.fill(list,new Integer(0));
    
    // this is better
    Integer[] data = new Integer[60];
    Arrays.fill(data,new Integer(0));
    List<Integer> list = Arrays.asList(data);
    
    0 讨论(0)
提交回复
热议问题