ArrayLists and Iterators
8. Capacity and Size
Answer:
ArrayList<Student> students = new ArrayList<Student>( 30 );
A rough estimate for the capacity is good enough. It is better to overestimate it than to underestimate it. A few unused cells do not hurt.
Capacity and Size
An ArrayList
object has a capacity and a size.
- The capacity is the total number of cells.
- The size is the number of cells that have data in them.
- Cells 0 up through size-1 have data in them.
- Data is added in order. Before cell N gets data, cells 0, 1, 2, ... N-1 must hold data.
The size increases by one each time an element is added. However, the capacity remains unchanged until the ArrayList
is full. When an element is added to a full list, the Java runtime system will greatly increase the capacity of the list so that many more elements can be added.
To find out the current size of an ArrayList
use its size()
method.
Question 8:
What is the capacity of the
ArrayList
in the picture?What is its size?