Java Program to Implement Dynamic Array

A dynamic array, also known as a ArrayList in Java, is an data structure that can grow or shrink in size dynamically as elements are added or removed. Dynamic arrays allow for changing the size of the array based on the number of elements it contains, while static arrays have a fixed size that cannot be modified. Dynamic arrays in Java are implemented using the ArrayList class, which provides methods to add, remove, and modify elements in the array. The ArrayList class also automatically handles resizing of the array as needed.

Working of Dynamic Array

  • A dynamic array is an array that can change its size during runtime.
  • In Java, dynamic arrays are implemented using the ArrayList class.
  • An ArrayList object has an initial capacity, which is the size of the underlying array used to store the elements.
  • When adding an element to the ArrayList and the underlying array is already full, the ArrayList will create a new array with a larger capacity and copy the elements from the old array to the new array automatically.
  • This process is called resizing and it allows the ArrayList to grow and shrink dynamically as needed.
  • Elements can be added to an ArrayList by using the add() method, and accessed using the get() method.
  • Similarly, elements can be removed from an ArrayList by using the remove() method.
  • Since dynamic arrays in Java are implemented using the ArrayList class, you don’t have to worry about memory allocation and management, which is taken care of by the Java Virtual Machine (JVM).

ArrayList Methods
ArrayList class provides several methods to manipulate the contents of the ArrayList. Here are some commonly used methods:

  1. add(index) – Add the element at the specified index.
  2. get(index) – Returns the element at the specified index.
  3. set(index, element) – Replaces the element at the specified index with the specified element.
  4. remove(index) – Removes the element at the specified index.
  5. size() – Returns the number of elements in the ArrayList.
  6. clear() – Removes all elements from the ArrayList.
Problem Description

Write a Java Program to implement Dynamic Array.

Program/Source Code

Here is the source code of the Java Program to implement Dynamic Array. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

/**
 ** Java Program to implement Dynamic Array
 **/
 
import java.util.Scanner;
import java.util.ArrayList;
 
/** class DynamicArray */
class DynamicArray
{
    private ArrayList<String> al;
 
    /** constructor **/
    public DynamicArray()
    {
        al = new ArrayList<String>();        
    }    
    /** function to clear **/
    public void clear()
    {
        al.clear();
    }
    /** function to get size **/
    public int size()
    {
        return al.size();
    }   
    /** function to insert element **/
    public void insert(String key)
    {
        al.add(key);
    }    
    /** function to get element at index **/
    public String get(int index)
    {
        if (index >= al.size())
            return "";
        return al.get(index);
    }
    /** function to remove element at index **/
    public void remove(int index)
    {
        if (index >= al.size())
            return ;
        al.remove(index);
    }   
    /** function to remove element **/
    public void remove(String key)
    {
        al.remove(key);
    } 
    /** function to display array **/
    public void display()
    {
        System.out.println("\nDynamic Array : "+ al);
        System.out.println();
    }              
}
 
/** Class DynamicArrayTest **/
public class DynamicArrayTest
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.println("Dynamic Array Test\n");   
 
        DynamicArray da = new DynamicArray();
 
        char ch;
        /*  Perform Dynamic Array operations */
        do    
        {
            System.out.println("\nDynamic Array\n");
            System.out.println("1. insert ");
            System.out.println("2. remove by index");
            System.out.println("3. remove by val");
            System.out.println("4. clear");
            System.out.println("5. size");
            System.out.println("Enter your choice:");
 
            int choice = scan.nextInt();            
            switch (choice) 
            {
            case 1 : 
                System.out.println("Enter value to insert");
                da.insert(scan.next() );                     
                break;                          
            case 2 : 
                System.out.println("Enter index");
                da.remove(scan.nextInt() );
                break;        
            case 3 : 
                System.out.println("Enter value");
                da.remove(scan.next() );
                break;                                   
            case 4 : 
                System.out.println("\nDynamic Array Cleared");
                da.clear();
                break;    
            case 5 : 
                System.out.println("\nSize = "+ da.size() );
                break;         
            default : 
                System.out.println("Wrong Entry \n ");
                break;   
            }    
            da.display();    
 
            System.out.println("\nDo you want to continue (Type y or n) \n");
            ch = scan.next().charAt(0);                        
        } while (ch == 'Y'|| ch == 'y');               
    }
}
Program Explanation

1. The program includes two classes: DynamicArray and DynamicArrayTest.
2. DynamicArray class contains the methods to perform operations on dynamic arrays such as clear(), size(), insert(), get(), remove(), and display().
3. The main logic for dynamic array operations is implemented in the main method of DynamicArrayTest class.
4. The program first creates an object of DynamicArray class.
5. A menu-driven console interface is provided for the user to perform various dynamic array operations.
6. The user is prompted to enter a choice from the menu and then perform the corresponding operation.
7. The program loops until the user chooses to exit.
8. When the user chooses an operation, the corresponding method of the DynamicArray class is called.
9. Finally, the current state of the dynamic array is displayed after each operation using the display() method.

advertisement
advertisement
Runtime Test Cases
Dynamic Array Test
 
 
Dynamic Array
 
1. insert
2. remove by index
3. remove by val
4. clear
5. size
Enter your choice:
1
Enter value to insert
apple
 
Dynamic Array : [apple]
 
 
Do you want to continue (Type y or n)
 
y
 
Dynamic Array
 
1. insert
2. remove by index
3. remove by val
4. clear
5. size
Enter your choice:
1
Enter value to insert
mango
 
Dynamic Array : [apple, mango]
 
 
Do you want to continue (Type y or n)
 
y
 
Dynamic Array
 
1. insert
2. remove by index
3. remove by val
4. clear
5. size
Enter your choice:
1
Enter value to insert
banana
 
Dynamic Array : [apple, mango, banana]
 
 
Do you want to continue (Type y or n)
 
y
 
Dynamic Array
 
1. insert
2. remove by index
3. remove by val
4. clear
5. size
Enter your choice:
1
Enter value to insert
strawberry
 
Dynamic Array : [apple, mango, banana, strawberry]
 
 
Do you want to continue (Type y or n)
 
y
 
Dynamic Array
 
1. insert
2. remove by index
3. remove by val
4. clear
5. size
Enter your choice:
5
 
Size = 4
 
Dynamic Array : [apple, mango, banana, strawberry]
 
 
Do you want to continue (Type y or n)
 
y
 
Dynamic Array
 
1. insert
2. remove by index
3. remove by val
4. clear
5. size
Enter your choice:
2
Enter index
2
 
Dynamic Array : [apple, mango, strawberry]
 
 
Do you want to continue (Type y or n)
 
y
 
Dynamic Array
 
1. insert
2. remove by index
3. remove by val
4. clear
5. size
Enter your choice:
3
Enter value
strawberry
 
Dynamic Array : [apple, mango]
 
 
Do you want to continue (Type y or n)
 
y
 
Dynamic Array
 
1. insert
2. remove by index
3. remove by val
4. clear
5. size
Enter your choice:
5
 
Size = 2
 
Dynamic Array : [apple, mango]
 
 
Do you want to continue (Type y or n)
 
y
 
Dynamic Array
 
1. insert
2. remove by index
3. remove by val
4. clear
5. size
Enter your choice:
4
 
Dynamic Array Cleared
 
Dynamic Array : []
 
 
Do you want to continue (Type y or n)
 
n

To practice programs on every topic in Java, please visit “Programming Examples in Java”, “Data Structures in Java” and “Algorithms in Java”.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.