ArrayList: how does the size increase?

后端 未结 19 823
既然无缘
既然无缘 2020-11-29 18:11

I have a basic question on Java ArrayList.

When ArrayList is declared and initialized using the default constructor, memory space for 10 el

19条回答
  •  南方客
    南方客 (楼主)
    2020-11-29 18:28

    When we try to add an object to the arraylist,

    Java checks to ensure that there is enough capacity in the existing array to hold the new object. If not, a new array of a greater size is created, the old array is copied to new array using Arrays.copyOf and the new array is assigned to the existing array.

    Look at the code below (taken from Java ArrayList Code at GrepCode.com).

    Check this example

    enter image description here

    Edit:

    public ArrayList() Constructs an empty list with an initial capacity of ten.

    public ArrayList(int initialCapacity) we can specify initial capacity.

    public ArrayList(Collection c) Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.

    Now when we use ArrayList() constructore we get a ArrayList with Size=10 On adding 11th element in the list new Arraylist is created inside ensureCapacity() method.

    Using following formula:

      int newCapacity= (oldCapacity * 3)/2 +1;
    

提交回复
热议问题