Java: How ArrayList manages memory

后端 未结 5 878
花落未央
花落未央 2021-01-12 17:13

In my Data Structures class we have studies the Java ArrayList class, and how it grows the underlying array when a user adds more elements. That is understood. However, I ca

5条回答
  •  遥遥无期
    2021-01-12 18:08

    The array size is never reduced automatically. It's very rare to actually have a list that is first filled with a large number of elements, then have it emptied but still kept around. And keep in mind that there must have been enough memory to hold the list (which consists only of references) and its elements - unlikely then that the memory consumed by the empty list would be a problem.

    If you really encounter an algorithm bizarre enough that this becomes a problem, you can still free the memory by calling trimToSize() manually.

提交回复
热议问题