|
发表于 2022-7-6 08:10:46
|
显示全部楼层
That's the usual fix for this scenario. All structures like collections use either linked lists, or such "growable" arrays as their base structure. If they use arrays they tend to keep the array slightly (or sometimes a lot) larger than the actual needed size. The most usual method is to grow the array to double its current size when its bounds is reached - this is so the extremely inefficient recreation of the array is not done many times over.
Note you need a separate variable to keep track of how many items are in fact used, since the bounds only shows "available-space" not "used-space". Some designs use one of the slots of the array to keep track of such. E.g. a Pascal String is an array of 256 bytes, the 1st of which contains the number of used characters. Another alternative is doing something similar to a C-String, where the last used slot contains a null value to indicate a "stop" - but this only works is null is not a valid normal value.
E.g. say the array bounds is (0 . 7), and you've used all 8 items from that. When you add another, you make a new array of (0 . 15), then copy each item from the old array into the new one, then add the new item. Then discard the old array. This is literally what happens with such "growable" arrays. Some implementations "might" be able to grow the array if the physical ram "in-front" of the array is not used by something else - but such happens very rarely. |
|