Java: How ArrayList manages memory

后端 未结 5 847
花落未央
花落未央 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:09

    They don't reduce the underlying array. They simply decrement the size. The reasoning for this is that if you have 1000 elements in an array and delete 1, why reallocate and copy the array? It's hugely wasteful for very little gain.

    Basically Java ArrayLists have two important properties and it's important to understand they are different:

    • size: how many elements are notionally in the List; and

    • capacity: how many elements can fit in the underlying array.

    When an ArrayList expands, it grows by about 50% in size even if you're only adding one element. This is a similar principle in reverse. Basically it comes down to this: reallocating the array and copying the values is (relatively) expensive. So much so that you want to minimize it happening. As long as the notional size is with a factory of about 2 of the array size, it's just not worth worrying about.

提交回复
热议问题