Java pass by reference issue with List -


this question has answer here:

i creating arraylist l1 , passing l1 reference method foo. know java doesn't support pass-by-reference here giving different results.

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 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 know java doesn't support pass-by-reference here giving different results.

apparently you've heard java supports pass-by-value. indeed correct. have realize java has references, , these can passed value.

in case reference list is passed method (although reference passed value).

the method uses reference modify original list, why see changes on "the outside" well.

see is java "pass-by-reference" or "pass-by-value"?


Comments