clearing or set null to objects in java

前端 未结 7 1650
盖世英雄少女心
盖世英雄少女心 2020-12-09 09:18

I was recently looking into freeing up memory occupied by Java objects. While doing that I got confused about how objects are copied (shallow/deep) in Java and how to avoid

7条回答
  •  南方客
    南方客 (楼主)
    2020-12-09 09:45

    It depends on how many variables are referenciating to each of your objects, to explain this it would be better some code:

    Object myAwesomeObject = new Object();
    List myList = new ArrayList();
    
    myList.add(myAwesomeObject);
    
    myList = null; // Your object hasn't been claimed by the GC just yet, your variable "myAwesomeObject" is still refering to it
    
    myAwesomeObject = null; // done, now your object is eligible for garbage collection.
    
    
    

    So it doesn't depend whether you pass your ArrayList as an argument to a method or the like, it depends on how many variables are still refering to your objects.

    提交回复
    热议问题