dynamic array in java code example

Example 1: 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++;
    }

Example 2: how to create dynamic string array in java

ArrayList<String> mylist = new ArrayList<String>();
mylist.add(mystring); //this adds an element to the list.

Tags: