Even if your array contains references to objects, which makes a variable reference to a completely different object, this will not change the contents of the array.
Your code does NOT modify the object variable a. This means that the variable a refers to another object as a whole.
Like your javascript code, the following java code will not work, because, like javascript, java passes object references by value:
Integer intOne = new Integer(1); Integer intTwo = new Integer(2); Integer[] intArray = new Integer[2]; intArray[0] = intOne; intArray[1] = intTwo; intTwo = new Integer(45); System.out.println(intArray[1]);
In Java, if you modify the object the variable refers to (instead of assigning a new variable reference), you get the desired behavior.
Example:
Thing thingOne = new Thing("funky"); Thing thingTwo = new Thing("junky"); Thing[] thingArray = new Thing [2]; thingArray[0] = thingOne; thingArray[1] = thingTwo; thingTwo.setName("Yippee"); System.out.println(thingArray[1].getName()); class Thing { public Thing(String n) { name = n; } private String name; public String getName() { return name; } public void setName(String s) { name = s; } }
source share