简体   繁体   English

sublist(from,to).clear()是否允许对ArrayList的清除部分进行垃圾回收?

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

In Java, when having some non-empty ArrayList, does 在Java中,当有一些非空的ArrayList时,

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

edit (refactored question): 编辑(重构的问题):

reduce the internal size of the ArrayList (ie let the ArrayList use less memory afterwards)? 减少ArrayList的内部大小(即让ArrayList之后使用更少的内存)?

I am particularly interested in the case where from = 0, ie where the list is cleared from the beginning until some item. 我特别关注from = 0的情况,即从头开始清除列表直到找到某项。 Does trimToSize() also work if from is any index inside the list (not only the first one)? 如果from是列表中的任何索引(不仅是第一个索引),trimToSize()是否也起作用?

"clear" is relocating objects in the underlying native array (an Object[]), but it doesn't resize the array. “清除”是在基础本机数组(Object [])中重新放置对象,但不会调整数组的大小。 If you want reduce the array size after removing some items in the ArrayList, use trimToSize() method. 如果要在删除ArrayList中的某些项目后减小数组大小,请使用trimToSize()方法。

Unused element references of the array are set to null, so the elements could be garbage collected. 数组的未使用元素引用设置为null,因此可以对元素进行垃圾回收。

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) 清除子列表时,与删除这些条目相同,因此可以对所有条目进行GC(除非在其他地方引用了它们)

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? sublist(from,to).clear()是否允许对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. 如果您修改其中一个,则更改可能在另一个上可见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM