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>();
}
}
Java passes references by value, think of
mySetas just a copy of thefooreference. Invoid test(Set<Integer> mySet), themySetvariable is just a local variable within that function, so setting it to something else doesn’t affect the caller inmain.mySetdoes reference(or “point to” if you like) the same Set as thefoovariable does inmainthough.If you want to alter the reference in main, you could do e.g.: