英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论