Part 1: What memory is allocated when the list object is created:
When an ArrayList is created with no default size, the following constructor is called:
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
super();
this.elementData = EMPTY_ELEMENTDATA;
}
super() here calls an AbstractList constructor which does nothing. this.elementData is set to an empty array of objects. Therefore, the memory allocated will be the sum of sizes of the different attributes of the ArrayList class + the 16 bytes allocated to the class itself:
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
private static final long serialVersionUID = 8683452581122892189L;
/**
* Default initial capacity.
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* Shared empty array instance used for empty instances.
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == EMPTY_ELEMENTDATA will be expanded to
* DEFAULT_CAPACITY when the first element is added.
*/
transient Object[] elementData; // non-private to simplify nested class access
/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
private int size;
....
You can checkout the default sizes of primitive data types and do the math to know the exact memory that is used.
But, no memory is used to store any data since an empty elementData array is initialized.
Part 2: how this memory size is allocated at run time if the size of the list grows dynamically.
Firstly we see that the ArrayList uses an array elementData to keep objects. There is a method that has amortized constant time that I can't exactly remember it's name.
But the idea is that when the array that the ArrayList class uses is filled, the size of the array is doubled. When the ArrayList elements are deleted and only 1/4 of the array is filled, the size of the array is halved.
ArrayList. 10*(memory size of reference toUserobject) + (overhead) is probably the initial memory allocatedsize()method does not have anything to do the actual memory allocated by the JVM for your list. You should probably do some reading first docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html, and then come back with some clear question.