0

I have a class A which contains:

List aList = new ArrayList();

aList .add("1");
aList .add("2");
aList .add("3");

Now class A.java contain a reference of another class B.java and class B.java contain another list with get() and set() method.

List bList;

In class A.java i am creating object of class B.java and calling setmethod of bList and giving A.java list to this method.

B b = new B();
b.setBList(aList);

But if aList is changed the value of bList also changed. How can i create a list even changing main*(aList)* list reference list will not change?

1 Answer 1

6

You need to make what is called a defensive copy:

b.setBList(new ArrayList(aList));

Note that this only copies the list itself, not the objects inside. So if someone calls a mutating method on the first object of the list, these changes will still be visible to B (obviously not a problem in your example, because Strings are immutable).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.