how to dynamically create array in java code example

Example: dynamic array in java

import java.util.Arrays;
public class DynamicArray{
    private int array[];
    // holds the current size of array
    private int size;
    // holds the total capacity of array
    private int capacity;
     
    // default constructor to initialize the array and values
    public DynamicArray(){
        array = new int[2];
        size=0;
        capacity=2;
    }
     
    // to add an element at the end
    public void addElement(int element){
        // double the capacity if all the allocated space is utilized
        if (size == capacity){
            ensureCapacity(2); 
        }
        array[size] = element;
        size++;
    }

Tags:

Java Example