Java memory allocation on stack vs heap

Amir Afghani picture Amir Afghani · Jul 20, 2010 · Viewed 7.7k times · Source

I feel like a novice for asking this question -- but why is it that when I pass the Set below into my method and point it to a new HashSet, it still comes out as the EmptySet? Is it because local variables are allocated on the stack, and so my new is blown away when I exit the method? How could I achieve the functional equivalent?

import java.util.HashSet;
import java.util.Set;

public class TestMethods {

    public static void main(final String[] args) {

        final Set<Integer> foo = java.util.Collections.emptySet();
        test(foo);

    }

    public static void test(Set<Integer> mySet) {

        mySet = new HashSet<Integer>();

    }

}

Answer

nos picture nos · Jul 20, 2010

Java passes references by value, think of mySet as just a copy of the foo reference. In void test(Set<Integer> mySet) , the mySet variable is just a local variable within that function, so setting it to something else doesn't affect the caller in main.

mySet does reference(or "point to" if you like) the same Set as the foo variable does in main though.

If you want to alter the reference in main, you could do e.g.:

foo = test(); //foo can't be final now though
 public static Set<Integer>  test() {
   return new HashSet<Integer>();
}