Expanding an Array? [duplicate]

The method does not change the value of OrigArray; all it does is store a clone of a clone in it, so in effect the value isn’t changed.

I think what you want is this:

public void expand() {
    String[] newArray = new String[OrigArray.length + 1];
    System.arraycopy(OrigArray, 0, newArray, 0, OrigArray.length);

    //an alternative to using System.arraycopy would be a for-loop:
    // for(int i = 0; i < OrigArray.length; i++)
    //     newArray[i] = OrigArray[i];
    OrigArray = newArray;
}

This creates an array that has a size 1 greater than OrigArray, copies the content of OrigArray into it and assigns that array to OrigArray. Unless you want to remember how many times expand() has been called, there shouldn’t be a reason to have the variable size.

EDIT: If what you really want is to know a way to sensibly implement the functionality you asked for, you can go with what @Óscar López said and use ArrayList.

Leave a Comment