Java pass by reference issue with List [duplicate]

两盒软妹~` 提交于 2019-12-13 07:43:28

问题


I am creating ArrayList l1 and passing l1 reference to the method foo. As we know that Java doesn't support Pass-By-Reference but here its giving different results.

See the below code

public static void main(String[] args) {
    List l1 = new ArrayList(Arrays.asList(4,6,7,8));
    System.out.println("Printing list before method calling:"+ l1);
    foo(l1);
    System.out.println("Printing list after method calling:"+l1);
}

public static void foo(List l2) {
    l2.add("done"); // adding elements to l2 not l1
    l2.add("blah");
}

Output:

Printing list before method calling:[4, 6, 7, 8]
Printing list after method calling:[4, 6, 7, 8, done, blah]

回答1:


As we know that Java doesn't support Pass-By-Reference but here its giving different results.

Apparently you've heard that Java only supports pass-by-value. This is indeed correct. But what you also have to realize is that Java has references, and that these can be passed by value.

In this case a reference to the list is passed to the method (although the reference is passed by value).

The method then uses this reference to modify the original list, which is why you see the changes on "the outside" as well.

See Is Java "pass-by-reference" or "pass-by-value"?



来源:https://stackoverflow.com/questions/30118452/java-pass-by-reference-issue-with-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!