如何在单个语句中初始化多个变量?

huangapple go评论59阅读模式
英文:

How to initialize multiple variable in single statement?

问题

JSONObject one = new JSONObject();
JSONObject two = new JSONObject();
JSONObject three = new JSONObject();

我尝试了以下方式

JSONObject one, two, three;
one = two = three = new JSONObject();

当我尝试在这些对象上写入时,出现错误。

[更新]

JSONObject one = null, two = null , three = null ;
one = two = three = new JSONObject();

one.put("test", 1);

英文:

I have below multiple variables.

JSONObject one = new JSONObject();
JSONObject two = new JSONObject();
JSONObject three = new JSONObject();

I tried below way

JSONObject one, two, three;
one = two = three = new JSONObject();

It is giving error when I am trying to write on those objects.

[UPDATE]

	JSONObject one = null, two = null , three = null ;
	one = two = three = new JSONObject();
	
	one.put("test", 1);

答案1

得分: 2

根据您的 [UPDATE] 部分,您可以这样做:

JSONObject one = null, two = null, three = null;
Stream.of(one, two, three).forEach(it -> it = new JSONObject());

但这仍然不是单语句初始化。

英文:

According to your [UPDATE] section you can do like this:

JSONObject one = null, two = null, three = null;
Stream.of(one, two, three).forEach(it -> it = new JSONObject());

But it's still not a single-statement initialization.

答案2

得分: 1

这取决于您想要实现什么。您自己发布的代码有效。

然而,您需要记住它只创建了一个对象,并将其分配给3个不同的变量。如果该对象是可变的,那么您需要小心。这基本上等同于这样:

JSONObject one = new JSONObject();
JSONObject two = one;
JSONObject three = two;

如果您想要创建3个不同的对象并将其分配给3个不同的变量,那是不可能的。

英文:

It depends on what you want to achieve. The code you posted yourself works.

one = two = three = new JSONObject();

However, you need to keep in mind that it creates only 1 object and assigns it to 3 different variable. If that object is mutable then you need to be careful. It is basicly equal to this:

JSONObject one = new JSONObject();
JSONObject two = one;
JSONObject three = two;

If you want to create 3 different objects and assign it to 3 different variable then it is not possible.

huangapple
  • 本文由 发表于 2020年8月7日 17:47:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/63299264.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定