Chaoz
Chaoz

Reputation: 2260

Should I do obj = null after arraylist.add(obj)

I was just wondering if we should do obj = null after adding it into an array. Note that this is about a special case, read below.

First, let's consider class A like this:

public class A {
    public void doSomething(B object) {
        // some code here
    }
}

and class B like this:

public class B {
    private final A a;
    public B(A a) {
        this.a = a;
    }
    public void aMethod() {
        // Does something here
        a.doSomething(this);
    }
}

Until now everything's ok. An object of type B can call the A's doSomething() method to edit the object based on some data there.

Now let's consider the following situation: the doSomething() adds the object B to an arraylist. Now which if these codes should I use:

public void doSomething(B b) {
    arrayList.add(b);
    b = null;
}
// or
public void doSomething(B b) {
    arrayList.add(b);
}

In the first doSomething() we set the object to null, which means that the method caller becomes null. Well, that's OK to me as doSomething() call is the last statement I need to in my aMethod(). But is it good to do so?

Upvotes: 2

Views: 89

Answers (2)

Makoto
Makoto

Reputation: 106470

No; it conflates the responsibility of doSomething too much. Why should it care what the lifecycle of whatever it has inserted in is?

It's also not going to have any effect. Due to Java being pass-by-value, you're only modifying the scoped value of b, and not wherever b originated from.

Code like that will only serve to confuse someone reading it down the road (and perhaps yourself), as the behavior in which you portray is misleading. If you're concerned about the lifecycle of the object you're inserting, note that so long as there's a reference it will not be eligible for garbage collection. This means so long as the collection you're adding it to isn't eligible, that reference isn't eligible either.

Upvotes: 5

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Just use:

public void doSomething(B b) {
    arrayList.add(b);
}

There is absolutely no need to set the parameter to null as it (the parameter, not the object that it refers to) no longer exists when the method exits.

Re

Note that this is about a special case, read below.

I see nothing special about your case.

In the first doSomething() we set the object to null, which means that the method caller becomes null. Well, that's OK to me as doSomething() call is the last statement I need to in my aMethod(). But is it good to do so?

Objects cannot be set to null, only variables and parameters (which are variables) can. You're confusing references with reference variables, a core distinction in Java.

Upvotes: 8

Related Questions