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.


/**
 * Main.java
 *
 * @author www.javadb.com
 */

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();
    }
}



So the output will look like this when the code above is executed:


Joe
Bill
Mary
Carl
Jane

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: