i was reading about how you can only pass by value in java and that the only way to swap the contents of two objects is by putting then in an array…passing the reference to the array object by value and then using that reference to swap 0-1 array location.
But i have a further question on this:
Suppose i create an array such as:
List<Integer> array = new ArrayList<Integer>();
Integer a = new Integer(1);
array.add(a);
So my question is when i “add” an object to an array (in this case Integer object)…do I just store the reference to the object in the array or do I actually copy the content of the object in the array…
Hypothetically, let’s say we have a “delete reference” statement in java,..so will this retain the value of the object in the array?
List<Integer> array = new ArrayList<Integer>();
Integer a = new Integer(1);
array.add(a);
delete a;
So will the array still hold the correct value??
Since we do not know what this hypothetical statement is doing, that is hard to tell.
What your ArrayList holds is a reference to an Integer object. Any other reference you have to that object points to the exact same instance.
With Integer, that does not make much of a difference, because Integer is immutable.
Try with a mutable object like StringBuilder to see the effect: