9

If I understand ArrayLists, they're backed by an array which is automatically resized when its full. On calling clear() is the ArrayList resized to the smallest possible array size?

4

4 回答 4

13

不,不是,这是一个需要牢记的问题。假设 ArrayList 的内部 Object[] 增长到 1000000 个元素。现在调用 ArrayList.clear()。这会将所有 1000000 个元素设置为 null,并将内部大小设置为 0。将 1000000 归零是一个耗时的操作,ArrayList 仍将占用堆上的 1000000 x 4 字节 Object[]。您可以在 clear() 之后调用 ArrayList.trimToSize() 但有一个问题 - 您首先清除了 1000000 个元素,然后将它们扔掉。在这种情况下,更好的解决方案是重新创建您的 ArrayList - new ArrayList()。

于 2012-12-22T13:50:05.877 回答
1

The size is set to 0 but there's no resize that happens explicitly
Here's the actual code.

     public void  clear() {
         modCount++;
         // Let gc do its work
         for (int i = 0; i < size; i++)
             elementData[i] = null;
         size = 0;
     }

Please check this link.

于 2012-12-22T09:53:08.973 回答
0

The size is set to zero. arrayList.clear() sets all the objects contained in an arraylist to null. But this does not ensure that all the objects contained in the arraylist will be garbage collected.The objects which have references elsewhere will not be Garbage collected till all references are removed.

于 2012-12-22T09:52:21.377 回答
0

要减小您可能需要在清除后使用 trimToSize () 的大小。通常这不会完成,因为除非您希望节省许多 MB,否则它不会产生太大影响。更常见的解决方案是在这种情况下替换 ArrayList。(我不是说那更好)

于 2012-12-22T11:13:42.590 回答