Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Was java.util.Arraylist#clear implemented the way it was in OpenJDK?

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?

like image 517
Sayo Oladeji Avatar asked Aug 14 '13 13:08

Sayo Oladeji


People also ask

Is Java Util an ArrayList?

The ArrayList class is a resizable array, which can be found in the java. util package.

Why we are using ArrayList in Java?

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.

Why we use ArrayList instead of list?

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.

What is Java Util arrays ArrayList?

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.


1 Answers

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.

like image 151
Sergey Kalinichenko Avatar answered Nov 14 '22 23:11

Sergey Kalinichenko