List subList()方法是否阻止垃圾回收列表的其余部分?(Does the List subList() method prevent garbage collection of the re

编程入门 行业动态 更新时间:2024-10-26 08:20:43
List subList()方法是否阻止垃圾回收列表的其余部分?(Does the List subList() method prevent garbage collection of the rest of the list?)

我很想知道最新的JVM如何处理由以下方法保留的垃圾收集内存。

public List<Player> getHallOfFame() { ArrayList<Player> listToSort = new ArrayList<Player>(map.values()); Collections.sort(listToSort, comparator); return listToSort.subList(0, 5); }

在最坏的情况下,我可以想象只要还有listToSort列表的引用,JVM就会将listToSort的全部内容listToSort在内存中。 有谁知道这是否确实如此? 我特别感兴趣的链接可以证明这种方式或其他特定的JVM。

I'm curious to find out how the latest JVMs would handle garbage collecting memory reserved by the following method.

public List<Player> getHallOfFame() { ArrayList<Player> listToSort = new ArrayList<Player>(map.values()); Collections.sort(listToSort, comparator); return listToSort.subList(0, 5); }

At worst I can imagine the JVM keeping the entire contents of listToSort in memory as long as there remain references to the sublist. Does anyone know if that is actually the case? I'm particularly interested in links that can prove this one way or the other for specific JVMs.

最满意答案

是的, subList只是对现有列表的“查看”。 所有数据都在原始列表中。 从文档:

返回的列表由此列表支持,因此返回列表中的非结构化更改将反映在此列表中,反之亦然。

所以是的,返回一个子列表将保持垃圾收集的原始列表。

如果你不想要这种效果,你基本上需要制作相关子列表的副本。 例如:

return new ArrayList<Player>(listToSort.subList(0, 5));

Yes, subList is only a "view" onto the existing list. All the data is really in the original list. From the documentation:

The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.

So yes, returning a sub-list will keep the original list from being garbage collected.

If you don't want that effect, you basically need to make a copy of the relevant sublist. For example:

return new ArrayList<Player>(listToSort.subList(0, 5));

更多推荐

本文发布于:2023-08-01 16:36:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1361577.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:垃圾   方法   列表   List   subList

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!