简体   繁体   中英

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:

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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