O'Reilly logo

Java™ Phrasebook by Timothy Fisher

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Resizing an Array

// use an ArrayList
											List myArray = new ArrayList();

In Java, regular arrays of objects or primitives can not be dynamically resized. If you want an array larger than what was originally declared, you’d have to declare a new larger array and copy the contents from the original array to the new larger array. Here we show how this is accomplished:

int[] tmp = new int[myArray.length + 10];
System.arraycopy(myArray, 0, tmp, 0,
myArray.length);
myArray = tmp;

In this example, we have an array of integers called myArray, and we want to expand the size of the array by 10 elements. We create a new array, which we call tmp, and initialize it to the length of myArray + 10. We then use the System.arrayCopy() method to copy the contents ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required