ArrayList.trimToSize() method

前端 未结 2 1390
广开言路
广开言路 2020-12-19 15:48

Can I use ArrayList.trimToSize() method in dynamic arrayList ?

  1. If I use it , what will be happened ?
  2. Can I get any benefits on using this method on dy
2条回答
  •  独厮守ぢ
    2020-12-19 16:31

    Well, that's simple:

    1. The ArrayList will be trimmed to its current size
    2. Yes, you can minimize the storage of an ArrayList instance
    3. When you want to trim the ArrayList and minimize its storage

    But seriously: There are few occasions where this method should be called (I personally have never used it). It's related to how an ArrayList is implemented: As the name suggests, the ArrayList internally uses an array to store the data. When you add new elements to the ArrayList, the size of the array is increased as needed. When you add 1000000 elements to the ArrayList, then the internal Array will have a .length of at least (!) 1000000. When you afterwards remove 999999 elements from the ArrayList, then the internal array will still have a .length of at least 1000000. The call to trimToSize will then make sure that the internal array only has the required size (1, in this case). But again: This is hardly ever necessary or beneficial. You should usually not work on ArrayList instances anyhow, but on the (more general) List interface.

提交回复
热议问题