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?

Joseph Quinsey
  • 9,185
  • 10
  • 53
  • 75
Subodh Joshi
  • 11,590
  • 25
  • 95
  • 188

1 Answers1

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

Thilo
  • 250,062
  • 96
  • 490
  • 643