Is this java Object eligible for garbage collection in List

后端 未结 4 556
难免孤独
难免孤独 2021-01-18 05:59

What I am asking might be a stupid question so please pardon me for that. So it goes like this :

List bossList = new ArrayList();
Bos         


        
相关标签:
4条回答
  • 2021-01-18 06:46

    Here's what really happens with your code :

    0 讨论(0)
  • 2021-01-18 06:47

    The Boss objects will not be collected by the GarbageCollector because they are still referenced in the code block that you are posted. bossList is an ArrayList which has an internal array of Object thus holding references to those objects which are added to it.

    I such a situation not only the references by you are considered but all referneces in all objects involved.

    EDIT: Since you are returning the List in your code the objects will not be marked for garbage collection until the list is no longer referenced in your program.

    0 讨论(0)
  • 2021-01-18 07:03

    Since java is pass by reference, whenever you add b to bossList, bossList starts referencing the memory location which b is pointing to. So when b nullified only link from b to the reference is broken. Thus keeping the object accessible through bossList.

    0 讨论(0)
  • 2021-01-18 07:05

    ArrayList has Object[] elementData internally. When you added b to bossList ArrayList assigned elementData[0] = b. So when you assigned null to b the instance of Boss is still referenced from elementData[0] and cannot be GCed. But since ArrayList instance is referenced only from method's variable after the method returns both ArrayList and Boss instances will be eligible for GC.

    0 讨论(0)
提交回复
热议问题