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.
If you do any changes to the sublist, it will affect the original list as well.
Java List sublist() Method. The sublist() method of List Interface returns a view of the portion of this list between the inclusive and exclusive parameters. This method eliminates the need for explicit range operations.
Sublist is a portion of List. The subList() method of java. util. ArrayList class is used to return a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
Method. Truncate a list to a size by removing elements at its end, if necessary. if (limit > items. size()) { return new ArrayList<>(items); final List<T> truncated = new ArrayList<>(limit); for (final T item : items) { truncated.
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));
subList
creates a new instance of AbstractList.SubList
, which keeps a reference to original list. So if you keep the variable returned by getHallOfFame
, it will prevent the gc to clean listToSort
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With