我觉得是个新手,但是为什么当我将下面的Set传递给我的方法并将其指向新的HashSet时,它仍然以EmptySet的形式出现?是因为局部变量分配在堆栈上,所以退出该方法时,我的和新的被吹走了吗?我怎样才能达到功能上的等同?

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按值传递引用,将mySet视为foo引用的副本。在void test(Set<Integer> mySet)中,mySet变量只是该函数中的局部变量,因此将其设置为其他值不会影响main中的调用方。
mySet确实引用(或“指向”,如果您愿意的话)与foo中的main变量相同的Set。

如果您要更改main中的引用,可以执行以下操作:

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

08-18 04:49
查看更多