Java通过引用传递列表的问题 [英] Java pass by reference issue with List

查看:109
本文介绍了Java通过引用传递列表的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建ArrayList l1并将l1引用传递给方法foo. 我们知道Java不支持Pass-By-Reference,但此处给出的结果有所不同.

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.

请参见下面的代码

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");
}

输出:

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

推荐答案

我们知道Java不支持Pass-By-Reference,但此处给出的结果有所不同.

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

显然,您听说过Java仅支持按值传递.这确实是正确的.但是,您还必须认识到Java具有引用,并且这些引用可以按值传递.

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.

请参见是Java的"pass-by-reference"吗?或按值传递"?

这篇关于Java通过引用传递列表的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆