Reputation: 63
i have two classes below, i want to learn what is the differencies between two type of assignement
Classes:
class ClassA {
public ArrayList<String> listA;
public ClassA() {}
}
class ClassB {
public ArrayList<String> listB;
public ClassB() {}
}
I want to put all my values of listB array to listA array, what is the differencies between below usage ? with second usage are there any reference between two classes that can be problem for garbage collector to delete objects. and what about usage3 ?
ClassA clsA= new ClassA();
ClassB clsB= new ClassB();
usage1
for (String s : clsB.listB) {
clsA.listA.add(s);
}
usage2
clsA.listA=clsB.listB;
usage3
clsA.listA=clsB.listB;
clsB.listB = null;
Upvotes: 2
Views: 68
Reputation: 1
As noted above, option 1 is NOT assignment. Precede by ClsA.lstB.clear() for copy.
Also, consider ClsA.lstA = (ArrayList) ClsB.lstB.clone();
This will provide a clean (shallow) copy of the target.
Upvotes: 0
Reputation: 5496
Usage 1: ListA will now have additional elements, those from listB.
Usage 2: ListA is now ListB, both references refer to the same object (assignment statement). If no current reference for the original ListA then it will be garbage collected.
Usage 3: ListA is now ListB (reference assignment like before), then right after, ListB is assigned to null (refers to nothing, a null pointer). If there's no current reference for the original ListA then it will be garbage collected.
I want to put all my values of listB array to listA array, what is the differencies between below usage ?
Usage 1 is what you want.
Upvotes: 2
Reputation: 18861
Upvotes: 2