0

I'm having some trouble understanding the third loop in my code below. After the second loop the list didn't change so I assumed that d was a copy of the element in the list. After the third output the element has its name changed so it's not a copy.

public class Test {
    public static void main(String[] args) {
        List<Dog> list = new ArrayList<>();

        list.add(new Dog("a"));
        list.add(new Dog("b"));
        list.add(new Dog("c"));
        list.forEach(d -> System.out.println("dog name: " + d.getName())); // a,b,c

        for (int i = 0; i < list.size(); i++) {
            list.set(i, new Dog("z"));
        }
        list.forEach(d -> System.out.println("dog name: " + d.getName())); // z,z,z
        for (Dog d : list) {
            d = new Dog("y");
        }
        list.forEach(d -> System.out.println("dog name: " + d.getName())); // z,z,z

        for (Dog d : list) {
            d.setName("w");
        }
        list.forEach(d -> System.out.println("dog name: " + d.getName())); // w,w,w

    }

    public static class Dog {
        private String name;

        public Dog(String n) {
            name = n;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}
Ced
  • 15,847
  • 14
  • 87
  • 146

2 Answers2

1

in your second for-loop, you are referencing the variable d to another Dog instance.

in your third for-loop, you are changing the instance.

William Ku
  • 798
  • 5
  • 17
1
    list.add(new Dog("a"));
    list.add(new Dog("b"));
    list.add(new Dog("c"));

This adds three Dogs to your list with names a, b, and c. They are then printed:

    list.forEach(d -> System.out.println("dog name: " + d.getName())); 

a,b,c

    for (int i = 0; i < list.size(); i++) {
        list.set(i, new Dog("z"));
    }

They are then being overwritten within the list (i.e., replaced) at index i (for all i in the range of the size of the list) by dogs with name z. They are all then printed:

    list.forEach(d -> System.out.println("dog name: " + d.getName())); 

z,z,z

You then created a new temporary reference to a dog for each dog in your list and name them all y. After the loop, this temporary reference goes out of scope, hence the dogs still being named z.

    for (Dog d : list) {
        d = new Dog("y");
    }
    list.forEach(d -> System.out.println("dog name: " + d.getName())); 

z,z,z

You then rename every dog in your list to w.

    for (Dog d : list) {
        d.setName("w");
    }

    list.forEach(d -> System.out.println("dog name: " + d.getName())); 

w,w,w

erip
  • 16,374
  • 11
  • 66
  • 121