Is it possible to set an Object to be null from within itself?

后端 未结 7 2024
情书的邮戳
情书的邮戳 2021-02-07 07:06

I know that this = null is illegal.

I\'m wondering if there\'s some other way to have an object clean itself up.

my desire is to be able to do some

7条回答
  •  被撕碎了的回忆
    2021-02-07 07:48

    You can't have an object set another object's reference to null like this without having them both aware of one another. Doing what you want is impossible without some legwork. I advise against the following example.

    public class A{
        A other;
        public A(A a){
            this.other = a;
            if(a!=null)
                a.other = this;
        }
        public void doSomethingAndDisappear(){
            a.other = null;
        }
    }
    

    This will cause one value's reference to a second reference to vanish as a second reference is setting the first reference's reference to null.

提交回复
热议问题