26hmkk 26hmkk - 4 months ago 13
Java Question

Adding a new column to a matrix/2d array

I know that arrays are supposed to have a constant number of elements in Java, but aside from this, arrays have served me very well in this application, so I don't wish to use a different data structure.

My issue seems to be in adding a new column to a 2d array. So far, I have:

String[][] tempArray = new String[array.length][array.length+1];


I then put all of the elements of the regular array
array
inside the one extra column long
tempArray
.

What I can't seem to do is put a new column in at the index of some
index
.

How would I go about this? Thanks!

Answer

Arrays are not dynamic in nature, so as far as I can tell, you cannot add columns to it. What you could do as a potential workaround, is to create another array with one extra column, and copy all values to it.

    int index = 7;
    String[][] array = new String[5][10];

    String[][] tempArray = Arrays.copyOf(array, array.length + 1); // New array with row size of old array + 1

    tempArray[array.length] = new String[array[index].length]; // Initializing the new row

    for(i=tempArray.length; i>=index; i--)
    {
        tempArray[i] = tempArray[i-1];
    }

    tempArray[index] = new String[array[index].length];

I know that you are averse to using any other data structures, but if you do change your mind, consider using an ArrayList.