Difference between length of Array and size of ArrayList in Java

Java 8Object Oriented ProgrammingProgramming

In collections, one of the main functional requirement is to get the number of elements which are get stored in our collection so that one can decide whether to put more elements in it or not. Also, the number of elements is also required for iteration of collection.

As we know Array and Arraylist both are used to store elements but both have different defined methods in order to know the number of elements stored in it.

The array has a length method that provides the number of elements can be stored or in simple words capacity of the Array. Also, the length method also defines the total space which has been allocated during the initialization of the array. Also during initialization what length we define of an array the same number of blocks are created of array type and JVM initializes every block by a default value.

On the other hand, ArrayList does not have length method but it has method named as size for calculating a number of elements get stored in it. As we know ArrayList grows dynamically as the elements are added to it. This happens in case of if the size of the current elements (including the new element to be added to the ArrayList) is greater than the maximum size of the array, a new Array is created of the same size and the old array is copied into the new array.

Published on 18-Sep-2019 12:23:03