Amila Bečirović Amila Bečirović - 6 months ago 16
Java Question

copy specific row from one 2D array to another without system.arraycopy

So I have to write a method that goes in array and goes from i to j rows and copies these rows to a new array. This is what I come up so far

public static void getRows(int i, int j, int[][] array){
int another[] = new int[j-i];
int n = 0;
for (int k = 0; k < array.length; k++){
while (i <= j){
if (k == i){
another[n] = array[k][0];
}
i++;
}
}
}

Answer

First, you aren't returning or printing anything. Second, to copy multiple rows from your input your returned array should be 2d (not 1d). Create a new int[][] of j - i rows. Then copy from array to the new array. Something like,

public static int[][] getRows(int i, int j, int[][] array) {
    int[][] ret = new int[j - i][];
    for (int k = i; k < j; k++) {
        ret[k - i] = new int[array[k].length];
        for (int m = 0; m < ret[k - i].length; m++) {
            ret[k - i][m] = array[k][m];
        }
    }
    return ret;
}

Then you can invoke it (and print the results) with something like

public static void main(String[] args) {
    int[][] t = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
    System.out.println(Arrays.deepToString(getRows(1, 3, t)));
}

Which outputs

[[2, 3], [4, 5]]
Comments