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 ...
Get Java™ Phrasebook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.