Mauren
Mauren

Reputation: 1975

Advantages of creating an ArrayList with initial capacity of 0?

I am a somewhat experienced Java developer and I keep seeing things like this

List<Integer> l = new ArrayList<Integer>(0);

which I really can't understand. What's the point of creating an ArrayList with an initial capacity of 0, when you know it's going to grow beyond the capacity?

Are there any known benefits of doing this?

Upvotes: 11

Views: 4196

Answers (6)

Craig Otis
Craig Otis

Reputation: 32104

It keeps the size (in memory) of the ArrayList very small, and is a tactic for when you want the variable to be non-null and ready to use, but don't expect for the List to be populated immediately. If you expect it to be populated immediately, it's best to give it a larger initial value - any "growing" of the ArrayList is internally creating a new primitive array, and copying items over. Growth of an ArrayList is expensive, and should be minimized.

Or, if you're creating lots of instances of a class that each contain one of these List properties. If you don't immediately plan on filling them, you can save a bit of memory by not allocating the room just yet.

However: There is a better way: Collections.emptyList(). Normally you'll want to protect access to that list directly, and (as an example) in your class provide domain-specific method calls that operate on the internal List. For example, let's say you have a School class that contains a List of student names. (Keeping it simple, note this class is not thread safe.)

public class School {
    private List<String> studentNames = Collections.emptyList();

    public void addStudentName(String name) {
        if (studentNames.isEmpty()) {
            studentNames = new ArrayList<String>();
        }
        studentNames.add(name);
    }

    public void removeStudentName(String name) {
        studentNames.remove(name);
        if (studentNames.isEmpty()) {
            studentNames = Collections.emptyList(); // GC will deallocate the old List
        }
    }
}

If you're willing to make the isEmpty() checks and perform the initialization/assignment, this is a better alternative to creating lots of empty ArrayList instances, as Collections.emptyList() is a static instance (only one exists) and is not modifiable.

Upvotes: 10

atish shimpi
atish shimpi

Reputation: 5023

It's always better approach to give a large value(if you how much list will exceed) to array list, because it will reduce resizing of list and hence optimize your execution time.

Initializing array list with value 0 create Empty array list which reducing memory if you know your list will not present more then 10 content's.

Upvotes: 1

Marcin Szymczak
Marcin Szymczak

Reputation: 11453

By default ArrayList has capacity of 10 and it is resized by +50% each time.

By using lower initial capacity you can sometimes(in theory) save memory. On the other hand each resize is time consuming. In most cases it is just a sign of preemptive optimization.

Upvotes: 2

vikingsteve
vikingsteve

Reputation: 40438

For java 6 (or openjdk 7), not specifying an initial size gives you a list within initial size set to 10. So depending on many factors of your usage of the list, it could be very slightly more memory and/or performance efficient to initialize the list with size 0.

For java 7, specifying an initial size 0 is functionally equivalent to not specifying an initial size.

However it is actually less efficient, since the call to the constructor with argument 0 incurs a call to new Object[0], whereas if you specify the no-args constructor, the initial elementData for your list is set to a statically defined constant named EMPTY_ELEMENTDATA.

Relevant code from ArrayList source:

/**
 * Shared empty array instance used for empty instances.
 */
private static final Object[] EMPTY_ELEMENTDATA = {};

In other words the use of new ArrayList<Integer>(0); seems superfluous, there are no benefits to doing so, and I would use new ArrayList<Integer>(); instead.

Upvotes: 8

flogram_dev
flogram_dev

Reputation: 42888

  • If additions to that ArrayList are really unlikely and if it's important to keep the size of the ArrayList at a minimum, then I can see that being useful.

  • Or if the only purpose of that ArrayList is to be a return value from a method, where returning an empty list is a special message to the function caller, like "no results found".

  • Otherwise, not really.

Upvotes: 3

barq
barq

Reputation: 3711

Depending on the contract you can avoid NullPointerExceptions by not having nulls. It is good practice in certain situations, see Effective Java by Joshua Bloch Item 43: Return empty arrays or collections, not nulls

Upvotes: -2

Related Questions