[英]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.