Friday, June 3, 2011

How to Extend the size of an array

This example shows how to extend the size of an array. Since arrays are static in size, they cannot be extended in the way collection objects can (for example a Vector). Hence we need to create a new array, add the new data and copy data from the first array. In this example we create an array with three names, then we create another array with the length of 5. We add two names to position 3 and 4 (which is really position 4 and 5 since the first element of an array has the index 0). Then we use the arraycopy() method of the System class and specify that we want to transfer data from the first position in the names array (param 1 and 2), and we want to insert the data in the array "extended" (param 3) from the first position (param 4) up to the length of the array "names" (param 5). Finally we print the elements of the extended array.

package org.best.examples;
public class Main {
   
    /**
     * Extends the size of an array.
     */

    public void extendArraySize() {
       
       
        String[] names = new String[] {"Joe", "Bill", "Mary"};
       
        //Create the extended array
        String[] extended = new String[5];
       
        //Add more names to the extended array
        extended[3] = "Carl";
        extended[4] = "Jane";
       
        //Copy contents from the first names array to the extended array
        System.arraycopy(names, 0, extended, 0, names.length);
       
        //Ouput contents of the extended array
        for (String str : extended)
            System.out.println(str);
       
    }
    /**
     * Starts the program
     *
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        new Main().extendArraySize();
    }
}

No comments: