javaarraylistcapacity

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?


Solution

  • 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.