如何深度复制二维数组(不同的行大小) [英] How to deep copy 2 dimensional array (different row sizes)

查看:23
本文介绍了如何深度复制二维数组(不同的行大小)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在这样的社区中的第一个问题,所以我的问题格式可能不是很好,首先抱歉.

This is my first question in a community like this, so my format in question may not be very good sorry for that in the first place.

现在我的问题是我想在 Java 中深度复制一个二维数组.在具有固定大小的行和列的 1 维甚至 2 维数组中执行此操作时非常容易.我的主要问题是我无法为我尝试复制的第二个数组进行初始化,例如:

Now that my problem is I want to deep copy a 2 dimension array in Java. It is pretty easy when doin it in 1 dimension or even 2 dimension array with fixed size of rows and columns. My main problem is I cannot make an initialization for the second array I try to copy such as:

int[][] copyArray = new int[row][column]

因为行大小不是固定的,每行索引都有变化,比如我尝试复制这个数组:

Because the row size is not fixed and changes in each row index such as I try to copy this array:

int[][] envoriment = {{1, 1, 1, 1}, {0, 1, 6}, {1}};

所以你看,如果我说 new int[3][4] 会有我不想要的额外空格.有没有办法对这种二维数组进行深度复制?

So you see, if I say new int[3][4] there will be extra spaces which I don't want. Is there a method to deep copy such kind of 2 dimensional array?

推荐答案

我认为您的意思是列大小不是固定的.无论如何,一个简单直接的方法是:

I think what you mean is that the column size isn't fixed. Anyway a simple straightforward way would be:

public int[][] copy(int[][] input) {
      int[][] target = new int[input.length][];
      for (int i=0; i <input.length; i++) {
        target[i] = Arrays.copyOf(input[i], input[i].length);
      }
      return target;
}

这篇关于如何深度复制二维数组(不同的行大小)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆