I have two version of code which truncate an existing list:
version 1:
List<String> myList = User.getAllNames();
myList = myList.stream().sorted(sortByName).limit(5).collect(Collectors.toList());
version 2:
List<String> myList = User.getAllNames();
myList.sort(sortByName);
myList = myList.subList(0, 5 - 1);
version 3:
List<String> myList = User.getAllNames();
myList = new ArrayList<BacktestResult>(myList.subList(0, 5 - 1));
You can assume, that no other objects have a reference to the clipped elements. Both versions truncate myList
by reassign. As version 2 uses only subList
which is baked by its origin list, I'm in doubt if version 2 also removes the clipped elements totally from the java heap (after garbage collection) like version 1 does.
The main thing I need to know is, if version 2 also removes the clipped elements totally from the java heap (after garbage collection) like version 1 does.
CodePudding user response:
I'm in doubt if version 2 also removes the clipped elements totally from the java heap (after garbage collection)
Assuming no other objects have a reference to the clipped elements, they will be eligible for garbage collection in the case of version 1.
In the case of version 2, since the sublist produced is a "view" of the original list, the sublist needs to keep a reference to the original list, which contains all the clipped elements. Therefore, those clipped elements will not be eligible for garbage collection.
Version 3 is similar to version 1. You discard the view produced by sublist
, so it will be eligible for GC. myList
becomes a new list that only has references to the first elements of the original. Now no variable directly or indirectly refers to the last elements of the original list, so they are eligible for GC.
That said, this will probably not matter unless your lists have a lot of elements.