I am a little confused as to how my Java program is allocating memory. Below is a typical situation in my program. I have an object created on the Heap inside of a class which I pass to other functions inside of other classes.
public class A { private List<Integer> list = new ArrayList<Integer>(); public A() { for(int i = 0; i < 100; i++) list.add(i); } public void foo() { B b = new B(); b.bar(this.list); } } public class B { A a = new A(); public int bar(List<Integer> list) { list.add(-1); return list.size(); } public int getSize() { List<Integer> list = a.list; return a.size(); } }
My question(s) are about how the memory is used. When A’s list gets passed to B.bar(), does the memory get copied? Java is pass-by-value so I assumed the B.bar() function now contains a copy of the list which is also allocated on the heap? Or does it duplicate the list and put it on the stack? Or is the list duplicated at all? Similarly what applies to these memory questions inside of B.getSize()?
Advertisement
Answer
It’s probably clearer to say that in Java, object references are passed by value.
So B gets a copy of the reference (which is a value) to the List, but not a copy of the List itself.
You can easily prove this to yourself by getting B to modify the List (by adding or removing something), and observing that A’s List also changes (i.e. it is the same List).
However, if you change B’s reference to the List (by creating and assigning a new List to it), A’s reference is unchanged.