Java如何手动删除对象

Java如何像C++一样删除对象

You should remove the references to it by assigning null or leaving the block where it was declared. After that, it will be automatically deleted by the garbage collector (not immediately, but eventually).

Example 1:

Object a = new Object();
a = null; // after this, if there is no reference to the object,
          // it will be deleted by the garbage collector

Example 2:

if (something) {
    Object o = new Object(); 
} // as you leave the block, the reference is deleted.
  // Later on, the garbage collector will delete the object itself.
posted @ 2022-04-12 14:52  Dre_am_tale  阅读(1529)  评论(0编辑  收藏  举报