ArrayList: how does the size increase?

后端 未结 19 822
既然无缘
既然无缘 2020-11-29 18:11

I have a basic question on Java ArrayList.

When ArrayList is declared and initialized using the default constructor, memory space for 10 el

19条回答
  •  独厮守ぢ
    2020-11-29 18:40

    A new array is created and the contents of the old one are copied over. That's all you know at the API level. Quoting from the docs (my emphasis):

    Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

    In terms of how it actually happens with a specific implementation of ArrayList (such as Sun's), in their case you can see the gory details in the source. But of course, relying on the details of a specific implementation isn't usually a good idea...

提交回复
热议问题