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.
Yes,
subListis only a “view” onto the existing list. All the data is really in the original list. From the documentation: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: