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];
}
}
}
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));
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With