JMitchell
JMitchell

Reputation: 1

Temporary variable changing main variable

I am trying to, inside a method, set a temporary variable equal to a predefined variable and modify the temporary variable and return it as an output. However along the way the predefined variable gets modified as well which causes an issue when I try to compare the modified variable to the original variable later. I have tried setting the original variable to final and tried to make the temporary variable new to no avail. I'm not sure how to sort out this bug, the code is like follows:

private static int[][] scanmap(int[][] map) {

          int[][] fillmap = mapzeros(map); //goal is to replace the map with zeros
          printMap(map);
          //checkboarder
          fillmap = mapboarder(fillmap, map);
          //keepadj
          fillmap = checkAdj(fillmap,map);
       return fillmap;
   }

in the mapzeros(map) method where the bug takes place

private static int[][] mapzeros(int[][] map) {
        int[][] tempmap = map; //temporary variable 
        for (int j =0; j < map.length; j++){
            for (int i =0; i < map[j].length; i++){
                tempmap[j][i] = 0;//why is this setting map[j][i] to 0???
                printMap(map); //shows the map 
            }
        }
        return tempmap;
}

Upvotes: 0

Views: 247

Answers (2)

maloomeister
maloomeister

Reputation: 2486

When you do this

int[][] tempmap = map; //temporary variable 

you don't create a copy of your initial array here, instead both tempmap and map point to the same array. This means of course, if you modify tempmap, you also modify the original array of map. Have a look at What is the difference between a deep copy and a shallow copy? for more information and in depth explanations on that topic.

What you need is a deep copy of your original object. I will not post any code here, since this topic has been discussed in many other Q&As already. So simply refer to How do I do a deep copy of a 2d array in Java? for working code to deep copy your array.

Upvotes: 2

Ayush Wadhwa
Ayush Wadhwa

Reputation: 89

Try to initialize tempmap like this

int[][] tempmap = new int[map.length][];
 for (int i = 0; i < map.length; i++) {
      tempmap[i] = Arrays.copyOf(map[i], map[i].length);
  }

Refer deep copy and shallow copy for more details.

Upvotes: 1

Related Questions