Hi,
I have a HashMap<Character, int[]> full of coordinates of letters in 5x5 table (char[5][5]), which I'm using for a cipher program I'm writing. Basically in order to encode each letter I take the coordinates of the letter and select a letter at different coordinates based on certain rules, but it wasn't working correctly for a reason which took me quite a while to work out. The problem was that I was creating an int array of the original coords, and then editing that array, thinking that it was just a copy and it should have no effect on the map, but it was affecting the map. I've recreated a very simple version of this problem, hopefully someone can tell me why this is happening.
import java.util.*; public class Cipher { public void test() { Map<Character, int[]> m = new HashMap<>(); int[] v = new int[2]; v[0] = 0; v[1] = 0; m.put('A', v); // coord should be a copy of the map value 'A' right? int[] coord = m.get('A'); // prints A : 0,0 as expected System.out.println(String.format("A : %d,%d", coord[0], coord[1])); // editing coord shouldn't affect the value in the map coord[0] = 1; coord[1] = 1; int[] newCoord = m.get('A'); // Map value for 'A' is now 1,1 System.out.println(String.format("A : %d, %d", newCoord[0], newCoord[1])); } public static void main(String[] args) { Cipher c = new Cipher(); c.test(); } }
This only happens when the value is an array. When i tried this with a Map<Character, Integer>, the map wasn't affected, as expected.
What is happening here? Why is the value of the first map being changed? Thanks in advance!