masterial
masterial

Reputation: 2216

How to slice a 2-D Java array?

folks,

I am working with JTables and have a 2-D array. I need to remove the first element of every row in the array. Is there a simpler way to do it besides?

int height = data2.length;
int width = data2[0].length;
Object[][] data = new Object[height][width];
for (int j=0; j<height; j++) {
    for (int i=1; i<width; i++) {
        data[j][i-1] = data2[j][i];
    }
}
data2 = data;

Thanks for your time!

Upvotes: 4

Views: 2273

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

Yes - you can use System.arraycopy instead of the inner loop:

Object[][] data = new Object[height][width];
for (int i = 0; i < height; i++) {
    System.arraycopy(data2[i], 1, data[i], 0, width-1);
}

Upvotes: 3

Related Questions