简体   繁体   中英

Java - Recursion - Matrix modification

I have an assignment where I am recursively modifiying a matrix of a custom type. Before the recursion, I am trying to make a copy of the matrix ("deep" copy with all attributes/variables of custom type). When the recursion returns however, the original matrix has been modified as if it was passed to the method recursively (and not the copy)

In the code below, "g" is modified after calling "a" with g2:

Copy functionality:

method a(Square[][]) {
    ...
    g2 = new Square[g.length][];
    for(int d = 0; d < g.length; d++) {
        g2[d] = Arrays.copyOf(g[d], g[d].length);
    }
    a(g2);
    //Here, g has been modified and not the original set of values
}

When you pass an array as a parameter, it is actually a reference point to the array, so when you are modifying the parameter within the method, you are also changing the values of the array directly. The best way to avoid your problem is to create a separate array and go value by value copying the values of the original array into it, before the recursive method is ever called. So that way you have your original array and your modified array by the end of the program.

Arrays.copyOf() produces a shallow copy which means any modification made to the original object will be reflected in the copy created.

I suggest you iterate over the array values and copy them to a new array in order to get a deep copy of the original array.

Arrays.copyOf does not perform a deep copy. You'll need to implement that yourself (and probably not use Arrays.copyOf at all).

This answer has some suggestions on how to implement your object copying: How do I copy an object in Java? (with copy constructors being the top advice).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM