[英]How to deep copy 2 dimensional array (different row sizes)
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. 这是我在这样的社区中的第一个问题,所以我的格式可能不是很好的抱歉。
Now that my problem is I want to deep copy a 2 dimension array in Java. 既然我的问题是我想在Java中深度复制二维数组。 It is pretty easy when doin it in 1 dimension or even 2 dimension array with fixed size of rows and columns.
使用固定大小的行和列在1维甚至2维数组中进行操作时非常容易。 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}};
So you see, if I say new int[3][4]
there will be extra spaces which I don't want. 所以你看,如果我说
new int[3][4]
会有额外的空间,我不想要。 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;
}
You don't have to initialize both dimensions at the same time: 您不必同时初始化两个维度:
int[][] test = new int[100][];
test[0] = new int[50];
Does it help ? 有帮助吗?
Java 8 lambdas make this easy: Java 8 lambdas使这很容易:
int[][] copy = Arrays.stream(envoriment).map(x -> x.clone()).toArray(int[][]::new);
You can also write .map(int[]::clone)
after JDK-8056051 is fixed, if you think that's clearer. 如果您认为JDK-8056051更加清晰,您也可以编写
.map(int[]::clone)
。
You might need something like this: 你可能需要这样的东西:
public class Example {
public static void main(String[] args) {
int[][] envoriment = {{1, 1, 1, 1}, {0, 1, 6}, {1}};
int[][] copyArray = new int[envoriment.length][];
System.arraycopy(envoriment, 0, copyArray, 0, envoriment.length);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.