开发者

What is the difference between "return new A()" and "return a = new A()"

开发者 https://www.devze.com 2023-04-12 10:53 出处:网络
I saw in many libraries, when returning some result, is used return a = new A() (e.g. return entrySet = new EntrySet()) instead of returning just new EntrySet(), what\'s t开发者_如何学Gohe difference

I saw in many libraries, when returning some result, is used return a = new A() (e.g. return entrySet = new EntrySet()) instead of returning just new EntrySet(), what's t开发者_如何学Gohe difference ?


The latter assigns a value to a before returning.

If a is local variable, it's almost certainly irrelevant. If a is an instance (or static) variable this will have a visible side-effect. It's sometimes used for sort of lazy initialization, e.g.

private String foo;

public String getFoo()
{
    if (foo != null)
    {
        return foo;
    }
    return foo = computeFoo();
}

private String computeFoo() { .. }


return a = new A() returns the value of the assignment of new A() to a. The value of an assignment is the value that was assigned.

So they both return the exact same value.

However return a = new A() also assigns the value to a. If a is a local variable, then this is an assignment that won't have any effect and should be removed. If a is a field, then this might be used to remember the last returned value for some reason.

In the latter case it will work, but I'd say that it's bad style (that line does more than 1 thing. Actually it does 3 things) and I'd rewrite it like this:

a = new A();
return a;


First things that comes to mind is "so you can inspect the return value inside the called method before actually exiting it". Honestly I've always thought both ways were equivalent.


If it's a local variable, there's no difference at all (after even a trivial amount of optimization). It's just a pointless assignment. But if it's an assignment to a field, that's just shorthand for:

this.a = new A();
return this.a;

Some people like to do it one way, some the other.


The result of an assignment is the value being assigned.

So in

 private int x;

 public int setX(int x) { return this.x = x; }

the setX method assigns its argument to this.x and returns the new value of this.x.


The difference is that the value is first assigned to a variable and then returned. If it's a local variable, this doesn't really have any effect as it will be out of scope as soon as the method returns. It would matter if it's an instance variable.

But I've never seen this kind of thing, and would consider it a rather dubious practice. What exactly tare the "mnay libraries" you've seen it being used in?

Update: I've just seen it being used in java.util.HashMap, apparently for lazy initialization of the entrySet field. I guess it makes sense for that kind of thing.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号