sublist(from,to).clear() 是否允许对 ArrayList 的已清除部分进行垃圾回收?
在Java中,当有一些非空ArrayList时,
list.sublist(from,to).clear()
编辑(重构问题):
是否会减少ArrayList的内部大小(即让ArrayList之后使用更少的内存)?
我对 from = 0 的情况特别感兴趣,即列表从头开始直到某个项目被清除。如果 from 是列表中的任何索引(不仅仅是第一个索引),trimToSize() 也可以工作吗?
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 memory 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)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
“clear”正在重新定位底层本机数组(Object[])中的对象,但它不会调整数组的大小。如果您想在删除 ArrayList 中的某些项目后减小数组大小,请使用 trimToSize() 方法。
数组中未使用的元素引用设置为 null,因此可以对这些元素进行垃圾收集。
"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.
当您清除子列表时,它与删除这些条目相同,因此所有这些条目都可以被GC(更少它们在其他地方被引用)
托管内存对象的全部要点是您不需要担心它们如何以及何时被清理干净。除非你知道自己有问题,否则我不会担心。在这种情况下,我将使用内存分析器来确定为什么在您认为不应保留对象时保留对象。
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.
是的,如果您获取子列表并清除它,您将从原始列表中删除子列表中的所有元素。
换句话说,如果列表是唯一存储对象引用的列表,您删除的对象就有资格进行垃圾回收。
基本演示:
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:
没用过?返回的列表是原始列表的视图。如果您修改其中一个,则更改可能会在另一个上可见。
Unused? That returned list is a VIEW of the original. If you modify one, changes may be visible on the other.