It keeps the size (in memory) of the ArrayList very small and is a tactic when you want a variable to be non-NULL and ready to use, but don't expect the List to populate immediately. If you expect it to be filled immediately, it is better to set it to a larger initial value - any "growing" ArrayList internally creates a new primitive array and copies the elements. The growth of an ArrayList expensive and should be minimized.
Or, if you create many instances of the class, each of which contains one of these List properties. If you do not plan to fill them out immediately, you can save some memory without having to allocate a room.
However: there is a better way: Collections.emptyList() . Usually you want to protect access to this list directly and (as an example) in your class provide method calls for a specific domain that work with the internal List . For example, let's say you have a School class that contains a List of student names. (Simply put, note that 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();
If you are ready to perform isEmpty() checks and perform initialization / assignment, this is the best alternative to creating a large number of empty ArrayList instances, since Collections.emptyList() is a static instance (there is only one) and is not mutable.
source share