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

前端 未结 6 1245
半阙折子戏
半阙折子戏 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:37

    This is most likely due to the case that the two constructor have different perceived default uses.

    The default (empty) constructor assumes that this will be a "typical ArrayList". Therefore, the number 10 is chosen as a sort of heuristic, aka "what the typical average number of elements inserted will be that will not take up too much space but will not grow the array needlessly too". On the other hand, the capacity constructor has the presupposition of "you know what you're doing" or "you know what you will be using the ArrayList for". Therefore, no heuristics of this type are present.

提交回复
热议问题