Java pass by reference issue with List

Anil Reddy Yarragonda

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]
aioobe

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"?

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related