繁体   English   中英

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

[英]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);

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

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

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

这取决于您想要达到的目标。 您自己发布的代码有效。

one = two = three = new JSONObject();

但是,您需要记住,它仅创建 1 个 object 并将其分配给 3 个不同的变量。 如果 object 是可变的,那么您需要小心。 基本上是这样的:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM