Resizing Arrays in Java

Arrays are fixed-size data structures and array sizes can not be changed once they have been initialized. However, in cases where array size needs to be changed, we have to follow one of the given approaches in this tutorial.

1. Using java.util.Arrays.copyOf()

The copyOf(originalArray, newLength) method takes an array and the new length of the array. The copyOf() creates a new array of required newLength and copies the originalArray to the new array using the System.arraycopy() function.

If the new array is smaller in size then copyOf() truncates the remaining items; else if the new array is bigger in size then it pads the remaining indices with nulls. The resulting array is of exactly the same type as the original array.

Note that copyOf() method resizes a one-dimensional array only. For resizing multi-dimensional arrays, there is no generic solution and we need to provide our own logic.

String[] originalArray = {"A", "B", "C", "D", "E"};
        
String[] resizedArray = Arrays.copyOf(originalArray, 10);

resizedArray[5] = "F";

System.out.println(Arrays.toString(resizedArray));
//[A, B, C, D, E, F, null, null, null, null]

There are few other APIs to resize the array but internally they follow the same approach, so we can skip them.

2. Using ArrayList

Another approach is to think again about your design. If an ArrayList is a better fit for such a usecase then consider using the List in place of the array.

Lists are already dynamically resizable, allow index-based accesses and provide great performance.

String[] originalArray = {"A", "B", "C", "D", "E"};

ArrayList<String> list = new ArrayList<>(Arrays.asList(originalArray));
list.add("F");

System.out.println(list);
//[A, B, C, D, E, F]

3. Conclusion

Resizing arrays in Java is no different than any other programming language. The resizing process allocates a new array with the specified size, copies elements from the old array to the new one, and then replace the old array with the new one.

In Java, we do not perform explicit memory management so the garbage collection takes care of the old array and frees the memory when it fits.

Happy Learning !!

Sourcecode on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode