Abdullah BAKMAZ
Abdullah BAKMAZ

Reputation: 63

Java reference and garbage collector

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

Answers (3)

Joe
Joe

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

NESPowerGlove
NESPowerGlove

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

MightyPork
MightyPork

Reputation: 18861

  1. No problem here, really, you just copy the values.
  2. You copy reference to the ArrayList. It's OK, just keep in mind that you now have only one ArrayList. Both A and B have the same reference.
  3. You basically move the B arraylist to A, and remove it from B. Again no problem.

Upvotes: 2

Related Questions