Why does list insertion fail when sufficient size is provided on construction?

前端 未结 8 880
北恋
北恋 2020-12-20 20:47

If we have the following variable declaration:

List list = new List(5);

Why does this:

list.insert(2, 3);
         


        
8条回答
  •  我在风中等你
    2020-12-20 20:58

    Because insert assumes that the list actually has that many items already inserted- capacity is not the same thing as size. Initializing the list with a given capacity just sets the size of the internal array- it is an optimization to prevent array resizes when you know the number of items that you are going to be inserting.

提交回复
热议问题