Sobes.tech
Junior — Middle

What amount of memory is freed when calling the clear method on a list containing 1 million Integer objects occupying 48 MB of memory?

sobes.tech AI

Answer from AI

When calling the clear() method on a list in Java, all references to the objects stored in the list are removed, meaning the list elements become inaccessible for further use through that list.

However, the list itself (for example, ArrayList) only releases memory for its internal array of references, not for the Integer objects themselves. The Integer objects remain in memory as long as there are references to them elsewhere.

If the list contained 1 million Integer objects and occupied 48 MB, then after calling clear():

  • The internal array of references is cleared (references are nulled), freeing the memory occupied by these references (approximately a few megabytes, depending on the implementation).
  • The Integer objects become eligible for garbage collection if there are no other references to them.

Thus, calling clear() frees the memory used by the list's internal structures and allows the garbage collector to reclaim the memory occupied by the objects if they are no longer used elsewhere.

Example:

List<Integer> list = new ArrayList<>();
// adding 1,000,000 elements
for (int i = 0; i < 1_000_000; i++) {
    list.add(i);
}
// memory usage approximately 48 MB

list.clear(); // references to objects are removed
// Integer objects can be garbage collected