0

I have this object ,which I label as the parent object, and I want to create a copy of that object which I call the child (method generate children).I implemented the copy by passing attributes of the parent to the constructor when I instantiated the child. The problem I keep encountering is that when I edit the child by calling an update method, the same modification happens to the parent. I need the parent to stay unchanged to give way to more copies, what could be the problem here? Any help appreciated :)

import javax.swing.*;
import java.util.*;


public class State
{
    private int[][] switches;
    private int[][] lights;
    private int numMoves;

public State(int[][] initSwitches,int[][] initLights,int numMoves)
{
    this.switches = initSwitches;
    this.lights = initLights;
    this.numMoves = numMoves;
}

public int[][] getSwitches()
{
    return switches;
}

public int[][] getLights()
{
    return lights;
}

public int getNumMoves()
{
    return numMoves;
}

public void updateState(int row, int col)
{
    this.toggleSwitch(row,col);
    this.toggleLight(row,col);

    if(row+1 <= 4)
    {
        this.toggleLight(row+1,col);
    } 

    if(row-1 >= 0)
    {
        this.toggleLight(row-1,col);
    }

    if(col+1 <= 4)
    {
        this.toggleLight(row,col+1);
    } 

    if(col-1 >= 0)
    {
        this.toggleLight(row,col-1);
    } 
}

public void toggleSwitch(int row, int col)
{
    if(this.switches[row][col] == 1)
    {
        this.switches[row][col] = 0;
    }

    else if(this.switches[row][col] == 0)
    {
        this.switches[row][col] = 1;
    }
}

public void toggleLight(int row,int col)
{
    if(this.lights[row][col] == 1)
    {
        this.lights[row][col] = 0;
    }

    else if(this.lights[row][col] == 0)
    {
        this.lights[row][col] = 1;
    }
}

public State[] generateChildren(int numChildren)
{
    int count = 0;
    State[] children = new State[numChildren];

    for(int i=0;i<numChildren;i+=1)
    {
        children[i] = new State(this.switches,this.lights,0);
    }       

    for(int i=0;i<5;i+=1)
    {
        for(int j=0;j<5;j+=1)
        {
            if(this.switches[i][j] == 0)
            {
                children[count].updateState(i,j);
                LightsOutSolver.printState(children[count]);
                count+=1;
            }
        }
    }

    return children;    
}   
 }

1 Answers1

0

when you create the children you pass to new State the same reference of the matrix switches and lights, so they are esactly the same object both in the parent and in the children. You need a deep copy. No time to explain, take a look at this How do I do a deep copy of a 2d array in Java?

Community
  • 1
  • 1
holap
  • 438
  • 2
  • 18