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

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

    but why would one inflate to 10 (a lot more than I asked for) and the other one to 1 (exactly as much as I requested)

    Probably because most people that create lists want to store more than 1 element in it.

    You know, when you want exactly one entry, why not use Collections.singletonList() for example.

    In other words, I think the answer is pragmatism. When you use the default constructor, the typical use case would be that you are going to add maybe a handful or so of elements quickly.

    Meaning: "unknown" is interpreted as "a few", whereas "exactly 0 (or 1)" is interpreted "hmm, exactly 0 or 1".

提交回复
热议问题