Subodh Joshi
Subodh Joshi

Reputation: 13492

Java reference of a List Issue?

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?

Upvotes: 0

Views: 110

Answers (1)

Thilo
Thilo

Reputation: 262474

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).

Upvotes: 6

Related Questions