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 of myArray to the tmp array. Finally, we set myArray to point to the newly created tmp array.

Generally, the best solution to this problem is to use an ArrayList object instead of a traditional array of objects. An ArrayList can hold any type of objects, and the major advantage of using it is that it dynamically resizes itself when necessary. With an ArrayList, you don't have to worry about the size of your array and whether you will run out of space. The ArrayList implementation is also much more efficient than using the method described previously to copy an array to a new array for resizing. The ArrayList is part of the java.util package.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net