[英]How to initialize multiple variable in single statement?
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);
According to your [UPDATE] section you can do like this:根据您的[UPDATE]部分,您可以这样做:
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.但这仍然不是单语句初始化。
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.但是,您需要记住,它仅创建 1 个 object 并将其分配给 3 个不同的变量。 If that object is mutable then you need to be careful.
如果 object 是可变的,那么您需要小心。 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.如果您想创建 3 个不同的对象并将其分配给 3 个不同的变量,那么这是不可能的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.