本文介绍了如何复制典雅,在Java中多维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
找出硬盘的方式,克隆()作为用于多维数组不工作后,现在我写
After finding out the hard way that clone() does not work as intended for multidimensional arrays, now I write
for(int k = 0; k < Nz; k++){
for(int j = 0; j < Ny; j++){
for(int i = 0; i < Nx; i++){
grid_copy[i][j][k] = grid[i][j][k];
}
}
}
每一个阵列。这种感觉让德pressingly水平低,抗干燥。任何人都可以提出这样做的更一般的方式?
for every array. This feels so depressingly low level and anti DRY. Could anyone suggest a more general way of doing this?
推荐答案
如果你真的真的想要一个普通的复印机,我只是这个翻飞在这里做了一些基本的测试。这很有趣,但我不认为这是更好,因为你的灵活性得到什么可读性丢失。
If you really really want a generic copier, I just whipped this up here and did some basic testing. It's interesting but I don't think it's any better because what you gain in flexibility is lost in readability.
private void copy(Object source, Object dest) {
if(source.getClass().isArray() && dest.getClass().isArray()) {
for(int i=0;i<Array.getLength(source); i++) {
if(Array.get(source, i) != null && Array.get(source, i).getClass().isArray()) {
copy(Array.get(source, i), Array.get(dest, i));
} else {
Array.set(dest, i, Array.get(source, i));
}
}
}
}
这篇关于如何复制典雅,在Java中多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!