Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to elegantly copy multidimensional arrays in Java?

Tags:

java

arrays

clone

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?

like image 707
Ivan Lappo-Danilevski Avatar asked Sep 01 '25 20:09

Ivan Lappo-Danilevski


1 Answers

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));
            }
        }
    }
}
like image 126
deraj Avatar answered Sep 03 '25 10:09

deraj