0

I am facing a problem with the code below, I know how to fix it, but I would like to understand why it behaves like this.

public void classTest() {
    Values v = new Values();
    ArrayList<Values> listV = new ArrayList<>();

    v.setValues(3.15);
    listV.add(v);
    System.out.println("v1: " + v.getValue());
    for (int i = 0; i < listV.size(); i++) {
        System.out.println("l1: " + i + " " + listV.get(i).getValue());
    }

    System.out.println();

    v.setValues(4.34);
    listV.add(v);
    System.out.println("v2: " + v.getValue());
    for (int i = 0; i < listV.size(); i++) {
        System.out.println("l2: " + i + " " + listV.get(i).getValue());
    }

    System.out.println();

    v.setValues(6.87);
    listV.add(v);
    System.out.println("v3: " + v.getValue());
    for (int i = 0; i < listV.size(); i++) {
        System.out.println("l3: " + i + " " + listV.get(i).getValue());
    }

}

The result is shown below. Note that items inside the ArrayList are all the same.

v1: 3.15
l1: 0 3.15

v2: 4.34
l2: 0 4.34
l2: 1 4.34

v3: 6.87
l3: 0 6.87
l3: 1 6.87
l3: 2 6.87

To fix I have to add v = new Values() before every setValues.

public void classTest() {
    Values v = new Values();
    ArrayList<Values> listV = new ArrayList<>();

    v.setValues(3.15);
    listV.add(v);
    System.out.println("v1: " + v.getValue());
    for (int i = 0; i < listV.size(); i++) {
        System.out.println("l1: " + i + " " + listV.get(i).getValue());
    }

    System.out.println();

    v = new Values();
    v.setValues(4.34);
    listV.add(v);
    System.out.println("v2: " + v.getValue());
    for (int i = 0; i < listV.size(); i++) {
        System.out.println("l2: " + i + " " + listV.get(i).getValue());
    }

    System.out.println();

    v = new Values();
    v.setValues(6.87);
    listV.add(v);
    System.out.println("v3: " + v.getValue());
    for (int i = 0; i < listV.size(); i++) {
        System.out.println("l3: " + i + " " + listV.get(i).getValue());
    }

}

Then result is:

v1: 3.15
l1: 0 3.15

v2: 4.34
l2: 0 3.15
l2: 1 4.34

v3: 6.87
l3: 0 3.15
l3: 1 4.34
l3: 2 6.87

Why is that? Why cant I just setValues again?

Thanks

Jms
  • 139
  • 14
  • 2
    Because when you add `v` in the loop you are adding a *reference* to `v`. So when you add something to `v` it is reflected across all the references to `v`. (i.e. all the items in your `ArrayList`) – GBlodgett Sep 19 '18 at 18:05
  • What this the best way of doing this? Is it possible to add what I have in `v` instead of adding `v` itself? – Jms Sep 19 '18 at 18:07
  • 1
    What do you mean? The best way of doing what? If you don't want to have an `ArrayList` full of references to the same object, simply make sure you're adding new objects. – GBlodgett Sep 19 '18 at 18:07
  • 1
    You could have a constructor to set the value that you want and then you could do something like `listV.add(new Values(4.34));` – GBlodgett Sep 19 '18 at 18:09

0 Answers0