Does appending/removing entries to a Java list reallocate memory?

假装没事ソ 提交于 2019-12-12 04:16:26

问题


This is low-level memory question about how Java performs .add and .remove on an ArrayList or other types of lists. I would think that Java would have to do a reallocation of memory to append/remove items to a list, but it could be doing something I'm not thinking of to avoid this. Does anyone know?


回答1:


If by "regular list" you mean java.util.List, that is an interface. It does not specify anything about whether or when any memory is allocated in association with adding or removing elements -- those are details of specific implementations.

As for java.util.ArrayList in particular, its docs say:

Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

In other words, Java does not specify the answer to your question.

If I were to speculate based on the available documentation, I would guess that java.util.ArrayList.remove() never performs any memory allocation or reallocation. It seems to follow from the docs overall that java.util.ArrayList.add() allocates additional space at least sometimes (in the form of a new, longer internal array). In order to achieve constant amortized cost for element additions, however, I don't see how it could reallocate on every element addition. Almost certainly, it reallocates only when its capacity is insufficient, and then it scales the capacity by a constant factor -- e.g. doubles it.




回答2:


All list implementations require storage of some information about the objects in the list and the order of those objects. Larger lists require more such information because there is some information for each object in the list. Thus adding to a list must, on average, result in allocation of more storage for this information.

Adding an element to a list does not copy the object that was added to the list. Indeed, no Java statements cause an additional copy of an object to be visible to your program (you have to explicitly use a copy constructor or a clone method to do that). This is because Java objects are never accessed directly, but are always accessed through a reference. Adding an object to a collection really means adding a new reference to the object to the collection.



来源:https://stackoverflow.com/questions/34617193/does-appending-removing-entries-to-a-java-list-reallocate-memory

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