如何在java中将一个二维数组存储在另一个二维数组中?

创建一个数组,您要在其中存储具有相同长度的现有数组。二维数组是一维数组的数组,因此,要复制(或对其执行任何操作)二维数组的元素,您需要两个嵌套在另一个中的循环。其中,外循环遍历一维数组的数组,内循环遍历特定一维数组的元素。

示例

public class Copying2DArray {

   public static void main(String args[]) {

      int[][] myArray = {{41, 52, 63}, {74, 85, 96}, {93, 82, 71} };

      int[][] copyArray =new int[myArray.length][];

      for (int i = 0; i < copyArray.length; ++i) {

         copyArray[i] = new int[myArray[i].length];

         for (int j = 0; j < copyArray[i].length; ++j) {

            copyArray[i][j] = myArray[i][j];

         }

      }

      System.out.println(Arrays.deepToString(copyArray));

   }

}

输出结果
[[41, 52, 63], [74, 85, 96], [93, 82, 71]]

以上是 如何在java中将一个二维数组存储在另一个二维数组中? 的全部内容, 来源链接: utcz.com/z/355854.html

回到顶部