java 列表边传边显示,Java通过引用传递列表的问题
发布日期:2022-03-15 11:50:03 浏览次数:12 分类:技术文章

本文共 1145 字,大约阅读时间需要 3 分钟。

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]

解决方案

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.

转载地址:https://blog.csdn.net/weixin_34614004/article/details/118823225 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:java.awt.image,为什么不是java.awt.image.BufferedImage中的序列化?
下一篇:武汉大学计算机作业,武汉大学计算机学院研究生操作系统作业.docx

发表评论

最新留言

很好
[***.11.154.38]2022年05月09日 16时01分24秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

最新文章