This week's giveaway is in the Spring forum.
We're giving away four copies of Learn Spring Security (video course) and have Eugen Paraschiv on-line!
See this thread for details.
Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Is Array List Default Size is Zero ?

 
vijay saraf
Ranch Hand
Posts: 141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ?
 
Rajesh Muppaneni
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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..

Cheers,
Raj..
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
vijay saraf
Ranch Hand
Posts: 141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks...........
 
Aditya Jha
Ranch Hand
Posts: 227
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic