1

Manipulating a List of String in Java

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]

}

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?

Submitted July 20th 2021 by Admin

Answers
0

1 ArrayList, 2 references

Your variables list2 points to the same ArrayList object as list1. You have 2 references but only 1 list. So making a change through either reference will be visible through both.

diagram showing two reference variables both pointing to the same ArrayList object

Admin | 6 days ago



Relevant Questions