Junior — Middle
What are the consequences of calling the clear method on an ArrayList object in Java?
sobes.tech AI
Answer from AI
Calling the clear() method on an ArrayList object in Java removes all elements from the list, making it empty.
Under the hood, the clear() method sets the list's size (size) to 0 and nullifies references to objects within the internal array, allowing the garbage collector to free memory if there are no other references to those objects.
After calling clear():
- The
ArrayListretains the same capacity (the internal array does not automatically shrink). - All elements are considered removed.
- You can add new elements starting from an empty list.
Example:
ArrayList<String> list = new ArrayList<>();
list.add("a");
list.add("b");
System.out.println(list.size()); // 2
list.clear();
System.out.println(list.size()); // 0
Thus, clear() effectively empties the list but does not free the internal array.