Java traversing a link with a list

I create an ArrayList l1 and pass the l1 reference to the foo method. As we know Java does not support Pass-By-Reference, but it gives different results here.

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

      

0


source to share


1 answer


As we know Java does not support Pass-By-Reference, but it gives different results here.

Apparently you've heard that Java only supports pass-by-value. This is really correct. But you also need to understand that Java has references and that they 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 that link to modify the original list, so you see the changes "outside" as well.

See Is Java "pass by reference" "or" skip by value ",

+1


source







All Articles