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);
Both versions truncate myList. 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.
Are there any differences between the two versions?
>Solution :
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.
That said, this will probably not matter unless your lists have a lot of elements.