Why does using different ArrayList constructors cause a different growth rate of the internal array?

前端 未结 6 1228
半阙折子戏
半阙折子戏 2021-02-05 15:31

I seem to stumble across something interesting in ArrayList implementation that I can\'t wrap my head around. Here is some code that shows what I mean:



        
6条回答
  •  时光说笑
    2021-02-05 15:50

    The capacity with the default constructor is 10 simply because the docs say so. It would have been chosen as a sensible compromise between not using up too much memory off the bat, and not having to perform lots of array copies when adding the first few elements.

    The zero behaviour is slightly speculative, but I'm fairly confident with my reasoning here:

    It's because if you explicitly initialise an ArrayList with a size of zero, then add something to it, you're saying "I'm not expecting this list to hold much, if anything at all." It therefore makes much, much more sense to grow the backing array slowly, as though it was initialised with a value of 1, rather than treating it as if it had no initial value specified at all. So it handles the special case of growing it to just 1 element, and then carries on as normal.

    To then complete the picture, an ArrayList explicitly initialised with a size of 1 would be expected to grow much more slowly (up to the point it hits the default "10 element" size) than the default one, otherwise there'd be no reason to initialise it with a small value in the first place.

提交回复
热议问题