File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Is Array List Default Size is Zero ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Is Array List Default Size is Zero ?" Watch "Is Array List Default Size is Zero ?" New topic

Is Array List Default Size is Zero ?

vijay saraf
Ranch Hand

Joined: Jan 08, 2005
Posts: 141
Hello All,

As per my knoladge ArrayList default size is 10 (if we don't provide any arg in new ArrayList()).But Look At following Program :
import java.util.*;
class defaultSizeTest
public static void main(String[] args)
ArrayList lArrayList = new ArrayList();
System.out.println("Hello World! "+lArrayList.size());
The out put is
Hello World! 0

Can any one Tell me why it happen so ?

Vijay Saraf.
Rajesh Muppaneni

Joined: Dec 27, 2004
Posts: 2
When you create an array list with the default constructor an array list is created with a capacity of 10..
The capacity is the size of the array used to store the elements in the list.
when you try to use size method of the array list you get the number of elements in the list.

Capacity and the Number of Elements in the list are different..

Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

size() returns the number of items currently in the list, which of course is zero when the list is created. What you're interested in the capacity, the size of the internal array including empty elements. I don't believe ArrayList offers an API that provides this information.

[Jess in Action][AskingGoodQuestions]
vijay saraf
Ranch Hand

Joined: Jan 08, 2005
Posts: 141
Aditya Jha
Ranch Hand

Joined: Aug 25, 2003
Posts: 227

Hi Vijay,

I guess your confusion is between capacity and size of an ArrayList.

First, let us just review how ArrayList works. As you might know, it has an array encapsulated inside, and the size of the array is its capacity. As and when the array is full, it allocates a larger array for storage. At any point in time, the number of elements array is holding is the real size of the list.

Simply put, CAPACITY of an ArrayList is the number of elements it can hold without spilling over, i.e., requiring to allocate a new array. Whereas SIZE is the exact number of elements it is holding.

Please go through the API document comments for this class. Using capacity and size judicially, one can make ArrayList objects perform pretty efficiently.

Hope this helps,

- Aditya
I agree. Here's the link:
subject: Is Array List Default Size is Zero ?
It's not a secret anymore!