Say goodbye to complex and rigid data structures and embrace the flexibility of “dynamic array in Java“. To understand the need to create a dynamic array in Java, letโs have a look at the fundamentals of arrays in Java in brief and its limitations. Apart from that if you have any doubts or issues related to other Java concepts then you can use CodingZap’s best Java assignment help, services, and Excel in your Java coursework.
Arrays are index-based data structures that store their elements in a linear fashion. They store the elements in contiguous memory locations, enabling faster access and retrieval of the elements.
The size of an array is fixed and can never be changed. It needs to be explicitly declared at the time of initialization. Because of this feature, arrays often give rise to a sense of limitation and constraint.
For example, let us suppose youโre making a to-do list for the week. It is not quite possible to precisely predict the size of your to-do list before you actually start jotting it down. In this case, you would want a data structure whose size can grow as the elements are added to the list.
We will therefore create our custom dynamic array, which has all the functionality of arrays with the added benefit of dynamic size. An additional benefit of creating a wrapper class for arrays is that we can add numerous other methods within the class definition that we may frequently use, such as printing the contents of the collection, among others. Also, are you curious to know the methods of printing an array?
What is the Implementation Process for Creating Dynamic Array? Read Below
We will create a wrapper โDynamicArrayโ class that internally uses an array to store its elements.
We will create the internal array with a default size and keep adding elements to it until it’s full.
Once the internal array reaches full capacity, we will generate a new internal array with double the size to compensate for the limited space.
We will copy all the elements from the previous array into the new array and then discard the previous array.
We will then utilize the newly created internal array as our primary array until it reaches full capacity, at which point we will repeat the process of creating another array to accommodate additional elements.
To have a more clear understanding of the concept of the array, you need to know the basic difference between Array and ArrayList.
Code To Demonstrate the Functionality of Dynamic Arrays and Resizing
import java.util.*; public class Main { public static void main(String[] args) { DynamicArray arr = new DynamicArray(); arr.add(1); arr.add(2); arr.add(3); arr.add(4); arr.add(5); for(int i=0; i<arr.size(); i++) System.out.print(arr.get(i)+" "); } } // Custom DynamicArray class class DynamicArray { private int[] array; // Internal array to store the elements private int size; // Number of elements currently in the array public DynamicArray() { // Initializing the dynamic array with a default capacity of 10 array = new int[10]; size = 0; } // Adds elements at the end of the array public void add(int element) { // If the internal array is full, resize the array if (size == array.length) { resizeArray(); } // Add the new element at the first available index array[size] = element; // Increment the size of the array size++; } // Retrieves an element at the specified index public int get(int index) { // Check if the index is valid if (index < 0 || index >= size) { throw new IndexOutOfBoundsException("Invalid index: " + index); } // Return the element at the specified index return array[index]; } // Returns the current size of the dynamic array public int size() { return size; } // Resizes the internal array to accommodate more elements private void resizeArray() { // Double the capacity of the new array int newCapacity = array.length * 2; // Create a new array with the increased capacity int[] newArray = new int[newCapacity]; // Copy the elements from the original array to the new array System.arraycopy(array, 0, newArray, 0, size); // Assign the new array as the internal array from now on array = newArray; } }
Output
1 2 3 4 5
In the above code, we have created a dynamic array of ints to demonstrate the functionality of dynamic arrays and resizing.
How to Create Our Dynamic Array to Make Use of Generics in Java?
Generics give us the power to choose our own type of data that we wish to hold in our collection. The compiler further enforces the type of data chosen and ensures that we only add the same type of elements in a particular collection, preventing type-related errors at compile time. This is called the type-safety feature of generics.
Generics also facilitate much easier code reusability, readability, and testability, making it a valuable tool for developers. Also, if you want to know how converting an object to an integer in Java works, you can check out our article. We have explained it in three easy ways.
Below is the code for our DynamicArray class incorporating the use of generics:
Code To Incorporate the Use of Generics
import java.util.*; public class Main { public static void main(String[] args) { // Creating a Dynamic Array of integers DynamicArray<Integer> arr = new DynamicArray<>(); // Adding 10 integers for(int i=1; i<=10; i++) arr.add(i*10); // printing the contents of the array arr.print(); // adding another 5 elements for(int i=11; i<=15; i++) arr.add(i*10); // printing the contents of the array arr.print(); // Creating a DynamicArray of String DynamicArray<String> s = new DynamicArray<>(); s.add("Using"); s.add("generics"); s.add("is easier"); s.add("than expected."); s.print(); } } // Custom DynamicArray class class DynamicArray<T> { private T[] array; // Internal array to store the elements private int size; // Number of elements currently in the array public DynamicArray() { // Initializing the dynamic array with a default capacity of 10 array = (T[]) new Object[10]; size = 0; } // Adds elements at the end of the array public void add(T element) { // If the internal array is full, resize the array if (size == array.length) { resizeArray(); } // Add the new element at the first available index array[size] = element; // Increment the size of the array size++; } // Retrieves an element at the specified index public T get(int index) { // Check if the index is valid if (index < 0 || index >= size) { throw new IndexOutOfBoundsException("Invalid index: " + index); } // Return the element at the specified index return array[index]; } // Returns the current size of the dynamic array public int size() { return size; } // Resizes the internal array to accommodate more elements private void resizeArray() { // Double the capacity of the new array int newCapacity = array.length * 2; // Create a new array with the increased capacity T[] newArray = (T[]) new Object[newCapacity]; // Copy the elements from the original array to the new array System.arraycopy(array, 0, newArray, 0, size); // Assign the new array as the internal array from now on array = newArray; } public void print() { System.out.print("Dynamic array: "); for(int i=0; i<size; i++) System.out.print(array[i]+" "); System.out.println(); } }
Output
Dynamic array: 10 20 30 40 50 60 70 80 90 100
Dynamic array: 10 20 30 40 50 60 70 80 90 100 110 120 130 140 150
Using generics is easier than expected.
In the above code, whenever the user calls the DynamicArray constructor, we create an array of the โObjectโ data type and type-cast it into the desired type as requested. We use type-castingย because we cannot use generics with arrays directly in Java. So we use the above method to work around this limitation.
As we can observe, our DynamicArray class is not just limited to the array of ints as in the previous code but can be used for any type of data required by the user.
Conclusion:
In this article, we looked at the basic features of arrays in Java and their limitations when it comes to a fixed size. We looked at how dynamic arrays may provide a solution to this limitation and the other benefits it offers.
We also understood the use of generics in Java and used it in our implementation of the DynamicArray class. Therefore, we developed a versatile dynamic array class definition that can cater to the user’s diverse needs.
If you have an interest in algorithms, you can check out our article on “Quick Sort Algorithm”
So, hope you have liked this piece of article. Share your thoughts in the comments section and let us know if we can improve more.