需要拆分此数组:
int[][] bitblock = {
{1,0,1,0,1,0,1,0},
{1,0,1,0,1,0,1,0},
{1,0,1,0,1,0,1,0},
{1,0,1,0,1,0,1,0},
{1,0,1,0,1,0,1,0},
{1,0,1,0,1,0,1,0},
{1,0,1,0,1,0,1,0},
{1,0,1,0,1,0,1,0}};
这是一个8 * 8数组,我想把它分成左右数组并存储在这里:
int[][] leftblock = new int [bitblock.length][bitblock[0].length/2];
int[][] rightblock = new int [bitblock.length][bitblock[0].length/2];
我使用了Syste.arraycopy方法,我能够将位块拆分为上下数组,我有点难以左右分割:
System.arraycopy(bitblock, 0, leftblock, 0, leftblock.length);
System.arraycopy(bitblock, rightblock.length, rightblock, 0, rightblock.length)
有人可以帮忙吗?感谢
答案 0 :(得分:2)
这应该很好地解决这个问题:
int[][] bitblock = {{1, 0, 1, 0, 1, 0, 1, 0}, {1, 0, 1, 0, 1, 0, 1, 0}, {1, 0, 1, 0, 1, 0, 1, 0}, {1, 0, 1, 0, 1, 0, 1, 0},
{1, 0, 1, 0, 1, 0, 1, 0}, {1, 0, 1, 0, 1, 0, 1, 0}, {1, 0, 1, 0, 1, 0, 1, 0}, {1, 0, 1, 0, 1, 0, 1, 0}};
int[][] leftblock = new int[bitblock.length][bitblock[0].length / 2];
int[][] rightblock = new int[bitblock.length][bitblock[0].length / 2];
for (int i = 0; i < bitblock.length; i++) {
for (int j = 0; j < bitblock[0].length / 2; j++) {
leftblock[i][j] = bitblock[i][j];
}
for (int j = bitblock[0].length / 2; j < bitblock[0].length; j++) {
rightblock[i][j - bitblock[0].length / 2] = bitblock[i][j];
}
}
int[][] leftblock = new int[bitblock.length][bitblock[0].length / 2];
int[][] rightblock = new int[bitblock.length][bitblock[0].length / 2];
for (int i = 0; i < bitblock.length; i++) {
for (int j = 0; j < bitblock[0].length / 2; j++) {
leftblock[i][j] = bitblock[i][j];
}
for (int j = bitblock[0].length / 2; j < bitblock[0].length; j++) {
rightblock[i][j - bitblock[0].length / 2] = bitblock[i][j];
}
}
您还可以使用System.arraycopy,因为它使代码更加清晰,以便将来检查。 至于性能,只要您的阵列很小,我认为这并不重要。
答案 1 :(得分:1)
对于8x8阵列,使用巧妙的阵列复制方法可能会带来最小的性能优势。我建议您使用嵌套for循环进行简单编码。代码将更简单,您将(可能)更快地完成工作。
答案 2 :(得分:0)
试试这个:
for (int i = 0 ; i < bitblock.length ; i++) {
System.arraycopy(bitblock[i], 0, leftblock[i], 0, leftblock[i].length);
System.arraycopy(bitblock[i], bitblock[0].length/2,
rightblock[i], 0, leftblock[i].length);
}
在这种情况下,我个人认为嵌套循环不会更好 - 你也可以使用System.arraycopy
的功能,而不是自己重新发明轮子。在我看来,这也比嵌套循环更易于管理/阅读。