Friday, November 11, 2016

Internal working of ArrayList

ArrayList is the most commonly used DataStructure in JAVA.

Internally it conatins an Array of Objects as follows ->
private transient Object[]elementData;

When we actually create an arrayList following piece of code is executed ->
this.elementData=new Object[initial capacity];



ArrayList can be created in two ways ->

1. List<String> myList=new ArrayList<String>(); 
(default constructor is invoked and internally creates an array of Object with default size 10)

2. List<String> myList=new ArrayList<String>(5);
(constructor with an integer argument is invoked and internally creates an array of Object with the size, specified in the constructor argument, which happens to be 5 in this case)



Unlike normal arrays, the size of the ArrayList grows dynamically.

Before adding element into the array it checks the current size of filled elements and the maximum size of the array. If the size of filled elements is greater than maximum size of the array then size of the array increases.

But since size of the array cannot be increased dynamically, internally a new Array is created with size 1.5 * currentSize and data from the old Array is copied into this new Array.

No comments:

Post a Comment

Home