Pregunta

Is it possible to change the dimensions of a two dimensional array in Processing?

int m = 4;
int n = 6;
int [][] nums = new int[2][3]; //right now the array has 2 rows and 3 columns

//code that changes the dimensions of the array to m x n

//setting nums.length and nums[0].length to m and n doesn't work, I tried it already
println(nums.length); //should be 4
println(nums[0].length); //should be 6

Here is an exact copy of the question:

Modify 2nd Dimension Write the following function:

void setDim(int[][] x, int m) {}

That changes the number of columns in each row of x to m.

Edit: I checked the answer, and the code that goes in the middle is

for(int i = 0 ; i < x.length; i++) x[i] = new int[m];

can someone explain this?

¿Fue útil?

Solución

It is not possible to change the size of the same array. The closest thing you can do is create a new one either with new operator and System.arraycopy() the data from the old one, or with Arrays.copyOf().

You may also consider using List instead of array. The size of List can be changed which might suit your task.

Regarding the second part of the question: two-dimentional array is an array of length let's say N, each item of that is an array of some length too. x[i] = new int[m] means:

  • Creating new int array of size m;
  • Setting reference to it into the x[i];

This is essentially the same - new arrays being created, the size is not modified.

Otros consejos

No, array length is established when it is created. After creation, its length is fixed.

However, you can use something like [System.arraycopy()](http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#arraycopy(java.lang.Object, int, java.lang.Object, int, int)), but in order to use it for two dimensional array I wrote this method that use System.arraycopy() to copy one array to another with the same order of elements:

public static void copy2dArray(Object src, Object dest){
     copy(src, 0, 0, dest, 0, 0)
}
private static void copy(Object src, int iSrc, int jSrc,  Object dest, int iDes, int jDest){

     int min=Math.min(src[iSrc].length-jSrc, dest[iDes].length-jDest);
     System.arraycopy(src[iSrc], jSrc, dest[iDes], jDes, min);
     if(min == src[iSrc].length-jSrc){
        iSrc++;
        jSrc=0;
        jDest=min;
        if(iSrc == src.length)
            return;
     }
     else{
         iDest++;
         jDest=0;
         jSrc=min;
         if(iDest == dest.length)
            return;
     }
     copy(src, iSrc, jSrc, dest, iDest, jDest);
 }

copy2dArray method will take two dimentional arrays and copy the first into the second with the same elements order,

For example: if this code got executed.

int [][] src = {{1, 2},
           {3, 4},
           {5, 6}};

int [][] dest = new int [2][4];

copy2dArray(src, dest);

The previous code will make
dest = {{1, 2, 3, 4}, {5, 6}}

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top