please, I'm having the code shown below:
public static void main(String[] args) {
List<String> list1 = new ArrayList<>();
list1.add("foo");
System.out.println("\nThis is list 1 : " +list1); //foo
List<String> list2 = list1;
System.out.println("\nThis is list 1 : " +list1); // foo
System.out.println("\nThis is list 2 : " +list2); // foo
List<String> list3 = new ArrayList<>(list2);
System.out.println("\nThis is list 3 : " +list3); // foo
list1.clear();
System.out.println("\nThis is list 1 : " +list1); // []
list2.add("bar");
list3.add("baz");
System.out.println("\nThis is list 1 : " +list1); // bar
System.out.println("\nThis is list 2 : " +list2); // bar
System.out.println("\nThis is list 3 : " +list3); // [foo, baz]
}
output:
**list 1 : [bar], list2 : [bar], list3 : [foo, baz]**
My question is how did list1 get the value bar? because I was thinking it was supposed to be empty at the time. And also, I was thinking that list2 is going to have the values [foo, bar] at this time. Please what is the logic behind this?


List<String> list2 = list1;does not make a newList. Change it toList<String> list2 = new ArrayList<>(list1);for that.