Search code examples
javagwtgwt2

Adding element to next free space in array


I have an array

String[] path={abc,bcd};

I pass this array in a method:

addElement(path);

In method

void addElement(String[] path)
{
    // here i got value suppose "qsd" and i want to add it after "bcd" ie 2 index of array
    path[path.lenght]="qsd"; 
}

But this is giving me an error.

I dont want to use an ArrayList.


Solution

  • The biggest problem is that arrays in Java are not trivially resizable. What you wind up doing instead is actually creating a new array, and adding each of the elements to that. This will be slower than the ArrayList code, and uglier as well.

    This also means that any code which points to the old array will no longer work. If you only have one instance, you could have addElement return the new array like so

    String[] addElement(String old[]){
        String arr[] = new String[old.length+1];
        //copy all the elements in old...
        arr[old.length] = "whatever";
        return arr;
    }
    

    Then use

    path = addElement(path);