Why Array list increase dynamically and not decrease dynamically [closed]

夙愿已清 提交于 2019-12-23 15:33:05

问题


I have a simple doubt , Arraylist increase its size with factor ( 2,1.5 or old_capacity*3/2 +1 or what ever) as it got full , and add new element in it. Then why dont it decrease it size dynamically if number is removed by some factor. Like if I have 10000 element in arraylist and at particular time all the elements are removed , only 100 elements are their in array list now It still hold 10000 object memory. Why i have to call trimTosize() or something? why it is not their automatically? Did I miss something .. ? Please dont tell me how to do it, I want to know why we have to do it ?? Thanks


回答1:


Then why dont it decrease it size dynamically if number is removed by some factor.

For performance reasons. Allocating memory is always an expensive operation. The logic behind not deallocating it, is that if your data structure has reached a given size, even if you remove elements, then it will probably reach that size again in the future.

Deallocating maybe also expensive too(this depends on the implementation but it's generally true. See realloc for C), because you may need to release the whole chunck of previously allocated memory, and then reallocate a new chunck for the resized structure.




回答2:


If an ArrayList is full and you want to add a new element there is no other way than increasing its size. If you delete entrys and the sizes gets smaller there is no actual need to resize it - leaving it at its size will be the more performant way. Maybe new items will be added soon?

If you want it to become smaller you can still use trimToSize().

Therefore it makes sense to increase its size automatically but it does not to decrease it automatically.




回答3:


Because if you have a list with, say, a million members, and remove one, do you really want to copy 999,999 references to a new array?

Edit: To address a concern in the comments - the problem with having some threshold at which the collection 'automatically' resizes is that it makes performance management difficult.

If I remove an element from an arraylist, I exepct that operation to take a certain amount of time. The 499,999th removal should take a similar amount of time to the 500,000th removal. If I really want to resize a collection at some point I can do that by using the provided method - but then its under my control.



来源:https://stackoverflow.com/questions/16188813/why-array-list-increase-dynamically-and-not-decrease-dynamically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!