http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/ArrayList.java#473
public void clear() {
modCount++;
// Let gc do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
My question is, why did they have to do an cycle through the backing array { O(n) } to make each element eligible for garbage collection when they could just have reinitialized the backing array, discarding references to the entire array as a whole { O(1) } and making it eligible for garbage collection?
O(n) performance for clear()
doesn't seem so nice to me or am I missing something?
The ArrayList class is a resizable array, which can be found in the java. util package.
ArrayList in Java is used to store dynamically sized collection of elements. Contrary to Arrays that are fixed in size, an ArrayList grows its size automatically when new elements are added to it. ArrayList is part of Java's collection framework and implements Java's List interface.
The List is an interface, and the ArrayList is a class of Java Collection framework. The List creates a static array, and the ArrayList creates a dynamic array for storing the objects. So the List can not be expanded once it is created but using the ArrayList, we can expand the array when needed.
The java. util. Arrays$ArrayList is a nested class inside the Arrays class. It is a fixed size or immutable list backed by an array.
Doing it the way they did lets you reuse the array without re-allocating its backing storage. If you wanted to reallocate the array, you could have done it yourself, since the representation of ArrayList
mostly consists of its backing storage.
If they released the array as a whole, there would be very little difference between calling clear()
and re-assigning the ArrayList
itself. Now they give you an option to choose between reusing the array or replacing it with a brand-new one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With