Skip to main content

Dynamic/Resizable Arrays

Execution/Test Class

Let us create an array with capacity as 4 and insert 9 numbers in it, the size of the array becomes 16.

Code

Following is the execution class

package dev.ggorantala.ds.arrays;

public class DynamicArrayExecution {
    private static final int[] INPUT = new int[] {1, 2, 3, 4, 5, 6, 7, 11, 9};

    public static void main(String[] args) {
        Array array = new Array(4);
        for (int value : INPUT) {
            array.insert(value);
        }

        array.remove(2); // removed element `3` from array

        System.out.println(array.get(0)); // 1
        System.out.println(array.size()); // 8

        // The extra o's are because of the array capacity which is 16
        array.print(); // 1, 2, 4, 5, 6, 7, 11, 9, 0, 0, 0, 0, 0, 0, 0, 0
    }
}

Illustrations & Explanation

We gave our array-like data structure with 9 elements {1, 2, 3, 4, 5, 6, 7, 11, 9}, But we initialized the size to 4 using Array array = new Array(4);.

A simple illustration is as follows:

So our array is ready to be loaded with input data. Our array instance size is 4, but we are inputting an array containing 9 elements.

After adding the first 4 elements from the input array, our array has reached its maximum capacity. Now the insert method doubles the array size and adds the next round of 4 elements. The following illustration explains.

After adding the first 8 elements from the input array, our array has reached its maximum capacity again. Now the insert method doubles the array size and adds the next round of 1 elements from the input array. The following illustration explains.

The insert method doubles its size when the array is insufficient and there are extra elements to add. So the size increases from 4 to 8, then from 8 to 16.

Note: Do not get confused about the size variable and how it's doubling itself. Check the insert method that does this trick when the array is full. This is the reason you are seeing extra zeros for print() method in above code.

This concludes the lesson.