Creating a Dynamic Array in Java
Updated on Feb 12, 2025 | 12 min read | 8.9k views
Share:
For working professionals
For fresh graduates
More
Updated on Feb 12, 2025 | 12 min read | 8.9k views
Share:
Table of Contents
An array is a data structure in Java that stores multiple elements of the same type in a contiguous memory location. However, traditional arrays have a fixed size, meaning their length cannot be changed after initialization. To overcome this limitation, a dynamic array in Java provides a flexible alternative by automatically resizing itself as elements are added or removed.
Unlike static arrays, dynamic arrays can expand or shrink based on the program’s needs, making them an essential data structure for efficient memory management.
This guide explores how to create and implement a dynamic array in Java, along with examples to help you understand its functionality.
A dynamic array in Java has the inherent ability to grow automatically when an insertion is made and no space is left for incoming data. This growth typically doubles the array's size, allowing it to overcome the limitations of a simple array. As a variable-size list data structure, it efficiently manages memory and provides flexibility.
When you create a dynamic array in Java, you can easily add or remove elements as needed. At runtime, memory is allocated using the heap concept, allowing dynamic resizing. The process starts by allocating a fixed-sized array, larger than the immediate requirement, ensuring efficient data handling.
Check out our free technology courses to get an edge over the competition.
The elements in a dynamic array are stored in the closest proximity from the starting of the array. Hence, after storage, the remaining spaces are left unused. Thus, this unused space is the limit to which elements can be added in a dynamic array.
There is a need to extend this fixed-sized array when the reserved space is consumed to full. There are two ways to achieve this.
Firstly, before adding the element, a bigger array is introduced. The elements from the fixed-sized previous array are copied to this new array. The system returns to this new array before adding the element.
In the second way, a function is created. This function creates a new array of double size, copies all the elements from the old array, and returns to the new array.
Both these ways can be implemented to shrink the size of any dynamic array in Java.
Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.
Being a data structure, the size and capacity of a dynamic array are not the same. The initialization of any dynamic array creates a fixed-sized array. When the number of elements is added to the array, they start taking their place just like A, B, C, D, and E in the image. The last five places are still empty. Thus, the length of this dynamic array size is five, but it can accommodate ten elements.
This is the difference between the size and capacity of a dynamic array in Java.
The following illustration explains how the elements are stacked in real-time in a dynamic array. Here, the size of the dynamic array is three, and the array’s capacity is six.
The following are the average case and worst-case real-time scenarios and how the instructions change accordingly.
In Java, a dynamic array is initiated like the same as a static array. Thus, it can be understood with the help of the following illustration:
Input:
Output:
The features of a dynamic array in Java are:
Any element can be added simply at the end of a dynamic array if it has space. If there is no space, then you need to extend the size of the array. After size extension, the element and index are added at the end of the original array.
This copy takes O (n) time, where n stands for the number of elements in the array. Hence, in the fixed-length array, the element only requires O (1) time. Thus, the time taken according to adding the element differs from O (1) to O (n).
If you need to add some more elements in a fixed-sized array, the following approach can be implemented.
Any element can be deleted from the dynamic array using the remove () or removeAt (i) method. The default remove () method stores zero at the last index after deleting the array element. The removeAt (i) method can delete the element at a specific index. The removeAt (i) is called that shifts all the elements on the left side from the given index “i.”
Resizing an array is essential when you need to add a new element in the dynamic array whose entire space has been utilized. In a case where a dynamic array has zero data at the right side and takes unrequited memory, srinkSize () method is used. It frees the extra memory. In other cases, resizing is achieved by allocating a bigger array, copying the elements from the old array, and adding the new element. The following illustration helps to understand the resizing of a dynamic array in Java.
Java provides several built-in dynamic array implementations that handle automatic resizing and efficient memory management. The most commonly used ones include ArrayList, LinkedList, CopyOnWriteArrayList, and Vector. Each of these structures has unique characteristics suited for different use cases, such as fast lookups, thread safety, or efficient insertions and deletions.
Let's discuss them below
The ArrayList is a resizable and non-synchronized array implementation of the interface ‘List’. It allows all items, including null, and implements all optional list operations. It also offers methods to alter the array size that is internally used to store the list. The following program illustrates several methods supported by ArrayList in Java:
Input:
Output:
It is a doubly linked non-synchronized list implementation of the deque and list interfaces. It implements all non-compulsory list operations and allows all elements, including the null. The following program illustrates several methods supported by LinkedList in Java:
Input:
Output:
It is an ArrayList’s thread-safe variant in which all operations like addition, setting, etc., are implemented by making a fresh copy of the previous array. It is highly efficient when the traversals operations exceed the addition, setting, etc. Like ArrayList, null is also permitted in CopyOnWriteArrayList.
It can employ a snapshot style iterator method that uses a reference to the array’s state at the point where the iterator was created. The interface is possible due to the fact that the array never changes during the iterator’s lifetime. The following program illustrates several methods supported by CopyOnWriteArrayList in Java:
Input:
Output:
It contains the components that can be accessed using an integer index. It implements a growable array of objects. After creating a vector, its size can grow or shrink according to the addition or removal of the elements. It is not a thread-safe implementation but is synchronized. It is the best replacement for the ArrayList. The following program illustrating several methods supported by Vector in Java:
Input:
Output:
Input:
Output:
A dynamic array in Java offers several advantages over traditional static arrays, making it a preferred choice for handling dynamic data structures.
Below are the key benefits:
Unlike static arrays, dynamic arrays automatically expand or shrink as elements are added or removed. This eliminates the need to define a fixed size beforehand, making them more flexible for varying data requirements.
Dynamic arrays allocate memory dynamically, reducing the risk of wasted space or memory overflow. When an array reaches its capacity, it creates a larger array and transfers the existing elements efficiently.
Similar to static arrays, dynamic arrays allow O(1) time complexity for accessing elements using an index, ensuring quick data retrieval.
While inserting or deleting elements in a static array requires shifting elements manually, dynamic arrays manage these operations more efficiently, especially when implemented using Java’s ArrayList.
Dynamic arrays are ideal for applications where data size is unknown or frequently changing. Their ability to grow and shrink as needed makes them a scalable solution for dynamic data handling.
While a dynamic array in Java offers flexibility and efficiency, it also has some limitations. Below are the key drawbacks:
When a dynamic array reaches its capacity, it needs to create a new, larger array and copy all elements. This process can be time-consuming and impact performance.
Dynamic arrays often allocate extra memory to reduce resizing operations. This can lead to unused memory space, making them less memory-efficient compared to linked lists.
Adding or removing elements in the middle of a dynamic array requires shifting elements. This results in O(n) time complexity, making operations slower compared to linked lists.
For applications handling massive data sets with frequent insertions and deletions, dynamic arrays may not be the best choice. Other data structures like linked lists or hash tables may perform better.
A dynamic array in Java stores elements of a single data type, limiting flexibility. If you need a collection with mixed data types, other structures like ArrayList<Object> or HashMap may be better options.
A dynamic array in Java is an efficient alternative to static arrays, allowing automatic resizing and dynamic memory allocation. It provides fast element access and improved flexibility, making it ideal for applications requiring variable-sized data storage. Unlike traditional arrays, dynamic arrays grow and shrink as needed, reducing memory wastage.
However, they come with certain limitations, such as resizing overhead and slower insertions due to element shifting. Despite these drawbacks, dynamic arrays remain a fundamental data structure in Java, widely used in programming for their adaptability and ease of management. Understanding their implementation helps in writing efficient Java applications.
Stay Ahead in Blockchain Technology! With the growing demand for crypto and blockchain expertise, now is the perfect time to upskill.
Enroll in upGrad’s Executive Post Graduate Programme in Software Development – Specialisation in Blockchain, offered in collaboration with IIIT Bangalore, and take your career to the next level
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources