简体   繁体   中英

How do I remove a specific row and a specific column from a 2D Array in Java?

If I have a method that accepts an int[][] , a row number to remove, and a column number to remove, how would I remove that specific row and column from the Array and return the new reduced Array?

I want to do it by taking everything except the row/column I want to remove and then putting it into two temporary ArrayLists, then constructing a new Array to return from the values in the two Arrays. I think I can remove a specific row just fine, however I don't know how to remove the column as well.

I think the best approach is create a new array of

int[xsize-1][ysize-1]

Have a nested for loop to copy from source array to destination. And skip for a specific i and j

static void TestFunction()
    {
        int rows = 5;
        int columns = 6;
        int sourcearr[][] = new int[rows][columns];
        int destinationarr[][] = new int[rows-1][columns-1];

        int REMOVE_ROW = 2;
        int REMOVE_COLUMN = 3;
        int p = 0;
        for( int i = 0; i < rows; ++i)
        {
            if ( i == REMOVE_ROW)
                continue;


            int q = 0;
            for( int j = 0; j < columns; ++j)
            {
                if ( j == REMOVE_COLUMN)
                    continue;

                destinationarr[p][q] = sourcearr[i][j];
                ++q;
            }

            ++p;
        }
    }

I'm trying to remove both 3 in two columns, under the index 2, how to achieve it?

public class For_petlja {

    public static void main(String[] args) {

        int[][] niz = {
            {9, 2, 3, 6, 7},
            {4, 7, 3, 5, 1}
        };
        int j;
        for (int i = 0; i < niz.length; i++) {
            for (j = 0; j < niz[i].length; j++) {
                if (i == 2) {
                    continue;
                }
            } // for 'j'
            System.out.println(Arrays.toString(niz[j]));
        } // for 'i'
    } // main method.
} // class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM