How to resize an array list in Java. – IT Blog
IT Blog
Boris IT Expert

How to resize an array list in Java.

Boris~November 3, 2020 /Array List

To resize the array in Java, you should follow several steps. The basic idea to create an empty array list with the needed length. And copy all elements from the first array list to the second.

Resize the array list in Java example. Step-by-step implementation.
If you want to resize the array list, you have to follow several steps:

resize array list java
 //The value of how many capacity suppose to be in a new array
        int capacity = 15;
//Creating empty array with needed capacity and then we will copy all values from our array
        int[] temporaryArray = new int[capacity];
//Now we need to copy values from first to second
        for (int i = 0; i < intArray.length; i++) {
//Setting first element of the temporary array to the value of first array... Etc...
            temporaryArray[i] = intArray[i];
        }

The full code example:

private void resizeOfTheArray() {
//Created a new array of integers
     int[] intArray = new int[]{1, 5, 3, 44, 5, 17, 78, 13, 9, 2};

//Get the length of the array
        int arrayLength = intArray.length;
//Showing in logs size of the array before resize
        Log.d("arrayList", "Old size of array: " + arrayLength);

//The value of how many capacity suppose to be in a new array
        int capacity = 15;
//Creating empty array with needed capacity and then we will copy all values from our array
        int[] temporaryArray = new int[capacity];
//We have created new empty array now we need to copy values from first to second
        for (int i = 0; i < intArray.length; i++) {
//Setting first element of the temporary array to the value of first array... Etc...
            temporaryArray[i] = intArray[i];
        }
//Setting first array to temporary and adjusting the size of it
        intArray = temporaryArray;

//Showing size of the array after resize
        Log.d("arrayList", "New size of array: " + intArray.length);
    }

In this article, you figured out the easiest way to resize an array list in java.

Full code and more examples in my facebook group.

Useful links:

Leave Any Questions Related To This Article Below!