Is there an append method for java arrays


I have several arrays in java, some ints, some strings etc... I would like to add (append) info to the end of them. How is this done?


Who is Participating?
basicinstinctConnect With a Mentor Commented:
Arrays in Java can't grow.  If you can't use an Arraylist or Vector then you will have to write code to make the array "grow".

Here's some code from this site:

Changing an Array’s Size in Array
An array’s length is a fixed length; to grow an array size you need to create a new array of the required size, and copy the existing elements in the old array to the new array, and fill in the rest with your new values.  Two ways to make a copy of an array:
1. Use loops (for, while, etc) to copy individual elements

    // Create the original array
    int[] originalArray = { 1,5, 14, 33 };
    // Define 2nd array
    int[] arrayCopy = new int[originalArray.length];
    // Copy individual elements
    for (int element = 0; element < originalArray.length; element++)
    arrayCopy[element] = originalArray[element];

2. Use System.arraycopy() method

    int[] originalArray = { 7, 4, 5, 2 };
    int[]arrayCopy = new int[originalArray.length];
    // Copy using arrayCopy()
    System.arraycopy(originalArray, // Source array
    0, // Source array position
    arrayCopy, // Target array
    0, // Target array position
And the code below from here:

    public int[] method01( SomeContainer rset )
        int[] bigArray = new int[ 1024 ];
        int count = 0;
        while( )
            if( count >= bigArray.length ) // time to grow!
                int[] tmpArray = new int[ bigArray.length + 1024 ];
                System.arraycopy( bigArray, 0, tmpArray,
                  0, bigArray.length );
                bigArray = tmpArray;
            bigArray[ count ] = rset.getInt();
            count += 1;
        int[] smallArray = new int[ count ];
        System.arraycopy( bigArray, 0, smallArray, 0, smallArray.length );
        return smallArray;
waffeAuthor Commented:
Thanks I have been looking into Arraylist and Vectors - running into a few problems but I'll post if I need some help.


Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.