Mighty
Mighty

Reputation: 387

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);

Upvotes: 0

Views: 924

Answers (2)

Nikolai  Shevchenko
Nikolai Shevchenko

Reputation: 7521

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.

Upvotes: 2

Amongalen
Amongalen

Reputation: 3131

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.

Upvotes: 1

Related Questions