1

Hi I´m trying to understand why is value of Arraylist reflected after assignment of value to the object in this simple example:

1.) I´m making instance of an object, with empty list as one of it´s attributes

2.) Adding value to the list

3.) Test object changes and is updated with values from the list

public Test makeTest(){
    ArrayList<String> clientIds = new ArrayList<>();
    Test test = new Test(clientIds);
    log.info("Test before:{}", test);

    clientIds.add("123_12_12");
    log.info("Test after:{}", test);

    return test;

}

Value of Test before adding to list: Test{clientIds=[]}

Value of Test after adding to list: Test{clientIds=[123_12_12]}

Why is the object created before adding to the list filled with these new values? Also another thing is, how do i stop this from happening?

I wanted to do something like test.setClientIds(clientIds); but it seems this is not necessary.

Daniel
  • 153
  • 1
  • 12
  • In addition to the previous comment you can pass `List.copyOf(clientIds)` to `Test`'s contructor – geobreze Nov 24 '21 at 18:50
  • You are passing the value of *a reference* to thr `Test` constructor, but that doesn't mean that the *whole `ArrayList`* is copied. No, you pass a reference to the constructor, which uses the reference to reach the object and call methods on it. This particular method (`add`) happens to *mutate* the object. The object itself is said to be *mutable*. If I give you a key to my house and you move the couch to the other corner of the living room, and you return the key to me, I enter my house seeing that my couch has been moved. – MC Emperor Nov 24 '21 at 18:55

0 Answers0