0

I'm currently working on a pathfinding algorithm called: Jump Point Search.

To check nodes I made an 2D Node array of nodes with a class "Node" (landSeaData). When I try to find a path I fill another global 2D Node array (tempWorld) with ".clone()" to make sure tempWorld isn't a pointer of landSeaData:

tempWorld = landSeaData.clone();

This clone method returns a new 2D Node array, but the indices are still pointer of the cloned array. I checked is with println:

System.out.println(tempWorld[1][0] +" , "+ landSeaData[1][0]);
Output: 
JPS.Node@4cc77c2e , JPS.Node@4cc77c2e

How do I prevent this or do I have to copy it another way, to make sure the indices are not pointers of each other?

EDIT

I've created a deep copier for the 2D array, but it takes to long, 47 milliseconds:

tempWorld = new Node[landSeaData.length][landSeaData[0].length];
for(int x = 0; x < landSeaData.length; x++) {
    for(int y = 0; y < landSeaData[0].length; y++) {
        if(landSeaData[x][y] != null) {
            tempWorld[x][y] = new Node(landSeaData[x][y].position);
        }
    }
}

Is there a faster way to deep copy?

M Zeinstra
  • 1,931
  • 4
  • 17
  • 46
  • `.clone()` is a "shallow copy", you want a "deep copy" which you'll have to implement yourself copying each element of the array to a new object before storing it in the new array. – ebyrob Dec 09 '15 at 14:45
  • @Tunaki I'm not sure this is a duplicate since it's asking about deep copying the elements (which may reference each other) not just the array structure in both dimensions. – ebyrob Dec 09 '15 at 14:53
  • You should allocate as little as possible if performance is an issue. If you know the maximum size of the array you are cloning, consider creating the cloned array only once and the Nodes only once. Just update or reset the member variables instead of instantiating the Node. – dreamwagon Dec 09 '15 at 15:10
  • @jjhavokk Thanks a lot! It's now down to 10 ms :)) Resetting the variables and don't create a new instance is a very good way to reset! – M Zeinstra Dec 09 '15 at 15:38

0 Answers0