Difference between Static Array and Dynamic Array
An array is a collection of similar types of data. Each data item present in the array is called the element of the array. The elements of the array share the same variable name but each element has a different index number. Arrays used to organize data and provide operations such as searching and sorting of data.
There are two types of arrays:
- Static Arrays
- Dynamic Arrays
Static Arrays
Static Arrays is a collection of similar types of data stored at contiguous memory location. Store multiple item of a same type together.
In Java:
char[] arr = new char[size of Array];
To access element:
0 based indexing.
arr[0] - 1st element of the array.
Size of arr = arr.length;
last element of the array = arr[arr.length-1];
Dynamic Arrays:
In dynamic array, we store the collection of similar types of element but we cannot define the size of the array. In Java dynamic array is created using ArrayList which is the implementation of List interface. When we declare the ArrayList, it creates an array with default size(i.e. 10) and when the array is full it creates a new array of double size and copies the elements of the old array and frees the space of the old array. The same method is followed in other programming languages also.Time complexity to insert an element is Amortized O(1).
In Dynamic Arrays, when the array becomes full then we create a new array of double the size of the old array and copy the elements of the old array to the new array and free the space occupied by the old array this whole operation takes O(n) time. But these operations are very few. So on average, we say that the overall insertion of an element takes Amortized O(1) time.
ArrayList<Object> arr = new ArrayList<>();
Comments
Post a Comment