Java 3x2二维数组按规则循环拷贝行的优化实现方案求助
解决方案
实现该移位操作的核心前提是先备份原始第一行的数据,避免直接覆盖后丢失原始值,这也是循环实现调试失败的常见原因
方案1:固定3行场景(简洁高效版)
直接调用JDK内置的System.arraycopy原生方法实现,性能优于手动逐元素赋值,代码更简洁:
import java.util.Arrays; public class ArrayShift { public static void main(String[] args) { int[][] m = {{3, 7}, {4, 8}, {5, 9}}; // 备份原始第一行数据 int[] originalFirstRow = Arrays.copyOf(m[0], m[0].length); int[][] n = new int[3][2]; // 第1行赋值为原第2行的值 System.arraycopy(m[1], 0, n[0], 0, m[1].length); // 第2行赋值为原第3行的值 System.arraycopy(m[2], 0, n[1], 0, m[2].length); // 第3行赋值为备份的原始第一行值 System.arraycopy(originalFirstRow, 0, n[2], 0, originalFirstRow.length); // 打印结果 for (int[] row : n) { for (int num : row) { System.out.print(num + " "); } System.out.println(); } } }
方案2:通用循环版(适配任意行列数)
如果后续数组的行数、列数可能发生变化,可以用通用循环实现,适配任意大小二维数组的行循环上移1位需求:
public class UniversalArrayShift { public static void main(String[] args) { int[][] m = {{3, 7}, {4, 8}, {5, 9}}; int rowCount = m.length; int colCount = m[0].length; // 备份原始第一行 int[] originalFirstRow = new int[colCount]; for (int j = 0; j < colCount; j++) { originalFirstRow[j] = m[0][j]; } int[][] n = new int[rowCount][colCount]; // 前n-1行依次赋值为下一行的原始值 for (int i = 0; i < rowCount - 1; i++) { for (int j = 0; j < colCount; j++) { n[i][j] = m[i+1][j]; } } // 最后一行赋值为备份的原始第一行值 for (int j = 0; j < colCount; j++) { n[rowCount - 1][j] = originalFirstRow[j]; } // 打印结果 for (int[] row : n) { for (int num : row) { System.out.print(num + " "); } System.out.println(); } } }
两种方案运行输出结果一致,完全符合需求:
4 8 5 9 3 7
内容的提问来源于stack exchange,提问作者Thomas
相关产品推荐
相关产品推荐

