开发者

Does sublist(from,to).clear() allow garbage collection of the cleared part of an ArrayList?

In Java, when having some non-empty ArrayList, does

list.sublist(from,to).clear()

edit (refactored question):

reduce the internal size of the ArrayList (i.e. let the ArrayList use less memor开发者_如何学Pythony afterwards)?

I am particularly interested in the case where from = 0, i.e. where the list is cleared from the beginning until some item. Does trimToSize() also work if from is any index inside the list (not only the first one)?


"clear" is relocating objects in the underlying native array (an Object[]), but it doesn't resize the array. If you want reduce the array size after removing some items in the ArrayList, use trimToSize() method.

Unused element references of the array are set to null, so the elements could be garbage collected.


When you clear a sublist, its the same as removing those entries, so all of them could be GCed (less they are referenced somewhere else)

The whole point of managed memory objects is that you don't need to worry about how and when they are cleaned up. I wouldn't worry about it unless you know you have a problem. In which case I would use a memory profiler to determine why objects are being retained when you think they shouldn't.


Does sublist(from,to).clear() allow garbage collection of the cleared part of an ArrayList?

Yes, if you get a sublist and clear it, you'll remove all the elements in the sublist from the original list.

In other words, if the list is the only one storing references to the objects, the objects you remove are eligible for garbage collection.

Basic demo:

List<String> strings = new ArrayList<String>();
strings.add("one");
strings.add("two");
strings.add("three");
strings.add("four");

System.out.println(strings);   // prints [one, two, three, four]

strings.subList(1, 3).clear();

System.out.println(strings);   // prints [one, four]


Unused? That returned list is a VIEW of the original. If you modify one, changes may be visible on the other.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜