简体   繁体   中英

Modifying a dataset after setting it in an Object

I have a Java question, but more object oriented related.

public class A {

    private List list;

    public A() {
        this.list = new ArrayList();
    }

    public List getList() {
        return this.list;
    }

    public void setList(List new_list) {
        this.list = new_list;
    }
}

public class Main {

    public static void main(String args[]) {
        A a = new A();
        List my_list = new ArrayList();
        a.setList(my_list);
        my_list.add("bla");
    }
}

The question: Is it allowed to the caller (main() in this example) to assume that setList(...) saves the reference to the List object?

To be specific - the last code line in the main() method - adding "bla" to my_list and assuming it will be added to A object's List as well.

Thanks in advance.

The answer is simply yes . Every assignment in Java uses the object reference by default, except for native types like int .

You are dealing with the references, not the real objects. Therefore when you call

List my_list = new ArrayList();
a.setList(my_list);

a reference to my_list is stored in a.list . Therefore you have two references of the same List object in your code my_list and a.list . Now, when you call

my_list.add("bla");

"bla" is added into the List object, which is being referred by a.list also. If you replace the above call by

a.getList().add("bla");

You would get the same result.

In your code, the caller ( main method) has a reference to the same list as the class A .

I think there is two options:

  • The setter method just save the reference (as in your code)
  • The setter method makes a preventive copy

The usual way that I see in my developer life is to save the reference. If you want to do a preventive copy, I think that should be in the javadoc. There is also people who always return an immutable version of the list to prevent modification of the state of your object. The choice is more about what you are doing here. If the do not trust the caller of your code, then do a preventive copy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM