I have a class called Program which hold a grid. It has two methods possi() which saves all possible ways you can enter the grid and saves ArrayList possi with all possible entry points and method solve which actually goes and enters the grid with the provided entry point. I’ve done mazesolvers using dfs and bfs but there my problem is that solve actually changes the grid substantially usually bfs and dfs dont account for the maze being changed. That is why I am not using them. I want to got through all the possibilities of entry points and further points. My first level of entry points is stored in lev1.possi and I can loop through them. Then I have to create a new instance of a grid since solve will change the structure and apply the solve then return new possi from that new object. So essentially I am creating a new object for each change. The problem is grid.clone() isnt making a new object instead still refering to my old grid.
Program lev1 = new Program();//initializes grid randomly
lev1.possi();//calculates entry points and stores in possi
ArrayList<Program> lev = new ArrayList<Program>();//stores all possible objects
for (int i = 0; i < lev1.possi.size(); i++)//loops through all entry points
{
Program pick = new Program(lev1.grid.clone());//makes a new object
lev.add(pick);
lev.get(i).solve(lev1.possi.get(i));//changes the new object
lev.get(i).possi();//calculates further points to go through
}
I assume
gridis some complex type, which contains complex types like an array, etc. In this caseclone()does not create a deep copy (i.e. it does not recursively clone the parts like an array).Here is an example of a
clone()method for complex types: In this example we have a typeFlightLogEntrywhich contains aTreeMap. To clone aFlightLogEntrywe need to create a newTreeMapand fill the map using the original elements. In this example those elements are not cloned (clone.setAttendant(p, this.attendats.get(p)). If you need an even deeper copy from the clone method (which depends on the usage of the clone) you might want to clone the attendat also like this:clone.setAttendant(p, this.attendats.get(p).clone().