How do I do a deep copy of a 2d array in Java?

前端 未结 6 1292
深忆病人
深忆病人 2020-11-22 02:07

I just got bit by using .clone() on my 2d boolean array, thinking that this was a deep copy.

How can I perform a deep copy of my bool

6条回答
  •  梦如初夏
    2020-11-22 02:41

    I'm a fan of the Arrays utility. It has a copyOf method that will do a deep copy of a 1-D array for you, so you'd want something like this:

    //say you have boolean[][] foo;
    boolean[][] nv = new boolean[foo.length][foo[0].length];
    for (int i = 0; i < nv.length; i++)
         nv[i] = Arrays.copyOf(foo[i], foo[i].length);
    

提交回复
热议问题