I am trying to work with lists in java and I am getting the following bug in my code(see below). I create a new list object L1 and pass it into function f. Inside function f I create a copy of L1 and name it L2. I do an add operation on L2 and return from the function. After I return the value of L1 has changed. How can this be? From what I understand the scope of L1 does not extend to function f, so L1 cannot be changed in function f. And L2 is a copy of L1 and is its own object so any changes to it should not change L1 either. Can someone explain this to me?
import java.util.List;
import java.util.ArrayList;
public class HelloWorld{
public static void main(String []args){
List<String> L1 = new ArrayList<String>();
L1.add("H");
L1.add("I");
System.out.println(L1);
f(L1);
System.out.println(L1);
}
public static void f(List<String> myList){
List<String> L2 = new ArrayList<String>();
L2 = myList;
L2.add("!");
return;
}
}
Which prints out
[H, I]
[H, I, !]