Java

How to Create a Dynamic Array in Java

The developers often face a limitation where there is a memory/size limitation while appending values in a container i.e., “array” in the case of updating the data. In such situations, a “Dynamic Array” comes into effect that expands the array size dynamically, thereby enabling the developer to append the required values at runtime.

This article will demonstrate the approaches to creating a “Dynamic Array” in Java.

What is a Java Dynamic Array?

The only limitation/issue of “Arrays” is that they are of fixed size. In such a case, the “Dynamic Arrays” come into effect that corresponds to a variable size list data structure. It is such that it increases its size automatically when adding an element in case of no more space for the new element.

How to Create a Java Dynamic Array?

In a “Dynamic Array”, the array increases/enhances its size and the entries/elements can be added to it. The new array size enhances to double the originally defined array’s size. It can be created via the following approaches:

Example 1: Creating an Integer Dynamic Array by Allocating the Array Size Twice

This example explains the procedure to create a “Dynamic Array” from the defined array by assigning its size as “twice”:

class Initarray {
 private int dynamicArray[];
 private int x;
 Initarray(int arrayLength) {
  dynamicArray = new int[arrayLength]; }
 public void displayArray(){
  for (int i = 0; i < x; i++) {
   System.out.print(dynamicArray[i] + " ");
}}
 public void add(int item){
  if (dynamicArray.length == x) {
   int newArr[] = new int[2 * x];
   for (int i = 0; i < x; i++) {
    newArr[i] = dynamicArray[i];
}
  dynamicArray = newArr;}
  dynamicArray[x++] = item;
}}
public class Dynamicarray {
 public static void main(String[] args){
  Initarray object = new Initarray(2);
  object.add(1);
  object.add(2);
  object.add(3);
  object.add(4);
  object.displayArray();
}}

 
According to the above code lines:

    • Define a class named “Initarray” comprising the specified array and an integer with “private” access modifiers, respectively.
    • Now, create a parameterized class constructor allocating the length of the array.
    • Define another function “displayArray()” that iterates along the array values and displays them via the “for” loop.
    • After that, declare the function “add()” having the stated parameter that points to the array values to be added.
    • It is such that before inserting the values, it checks for the array length and “x” variable. If both are of the identical/same size, it implies that the array is full.
    • In such a case, create a new array having a size twice the size of the former array, thereby accumulating the additional values inserted in the array.
    • Also, initialize the new array with the former array and reinitialize it back to the former array.
    • In “main”, create a class object using the “new” keyword and the “Initarray()” parameterized constructor specifying the array size i.e., “2”.
    • Also, invoke the defined function “add()” and insert the stated integer values in it.
    • Lastly, access the “displayArray()” function to log the added values.

Output


In the output, it can be analyzed that “4” values are inserted in the array despite the array’s size being “2”.

Import the following package in the next example to access all the functionalities in the “java.util” package:

import java.util.*;

 
Example 2: Creating a User-Input String Dynamic Array Using “ArrayList”

In this specific example, a user-input “Dynamic Array” can be created via “ArrayList”:

public class Dynamicarray2 {
 public static void main(String[] args){
  Scanner object = new Scanner(System.in);
  System.out.println("Input the array size: ");
  int arraySize = object.nextInt();
  String array[] = new String[arraySize];
  System.out.println("Input the array elements: ");
  for(int i= 0; i<arraySize; i++){
   array[i] = object.next();
}
  System.out.println(Arrays.toString(array));
  ArrayList<String> givenList = new ArrayList<String>(Arrays.asList(array));
  System.out.println("Input the element to be added/appended:");
  String item = object.next();
  givenList.add(item);
  array = givenList.toArray(array);
  System.out.println(Arrays.toString(array));
}}

 
In these code lines:

    • Input the array size from the user via the created Scanner object’s “System.in” parameter.
    • Ensure the input array size is an integer via the applied “nextInt()” method.
    • Now, define a “String” array comprising the user input array size.
    • After that, iterate through the array elements and return them in the form of a “String”.
    • Also, create an “ArrayList” to add a new value to the array, thereby increasing the array size via the “add()” method and returning it as a “String” as well.

Output


In this outcome, it can be observed that the user input array size is “3” but the added values are “4”. This implies that a “Dynamic Array” is created successfully.

Conclusion

A “Dynamic Array” increases its size automatically when we try to add an element and can be created via a new array having the size twice as the already defined array or via the “ArrayList”. This write-up guided to create a “Dynamic Array” in Java.

About the author

Umar Hassan

I am a Front-End Web Developer. Being a technical author, I try to learn new things and adapt with them every day. I am passionate to write about evolving software tools and technologies and make it understandable for the end-user.