How to implement our own Dynamic Array class in Java?
ArrayList is same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
- ArrayList elements are placed in contiguous storage so that they can be accessed and traversed using iterators.
- In ArrayList, data is inserted at the end.
- Inserting at the end takes differential time, as sometimes there may be a need of extending the array.
- Removing the last element takes only constant time because no resizing happens.
- Inserting and erasing at the beginning or in the middle is linear in time.
Functions to be implemented in the Dynamic array class:
Certain functions associated with the ArrayList that we will implement are:
- void push(int data): This function takes one element and inserts it at the last. Amortized time complexity is O(1).
- void push(int data, int index): It inserts data at the specified index. Time complexity is O(1).
- int get(int index): It is used to get the element at the specified index. Time complexity is O(1).
- void pop(): It deletes the last element. Time complexity is O(1).
- int size(): It returns the size of the ArrayList i.e, number of elements in the ArrayList. Time complexity is O(1).
- int getcapacity(): It returns the capacity of the ArrayList. Time complexity is O(1).
- void print(): It is used to print array elements. Time complexity is O(N), where N is the size of the ArrayList.
Implementation of the Dynamic array class:
Below is the implementation of our own ArrayList class.
ArrayList size: 5 ArrayList capacity: 8 ArrayList elements: 10 20 30 40 50 After updating 1st index ArrayList elements: 10 100 30 40 50 Element at 1st index: 100 After deleting the last element ArrayList size: 4 ArrayList capacity: 8 ArrayList elements: 10 100 30 40