AJW
AJW

Reputation: 5863

declare multiple arraylists

is it possible to declare 2 array lists in the same line? e.g:

List<String> mm= new ArrayList<String>();
List<String> kk= new ArrayList<String>();

Is it then possible to do something like:

List<String> mm,kk= new ArrayList<String>();

Obviously, I get a compile error when I do the above, and was wondering how could one declare 2 lists in the same line.

Upvotes: 2

Views: 4848

Answers (4)

fge
fge

Reputation: 121712

If you want that, you should do:

List<String> list_1 = new ArrayList<String>(), list_2 = new ArrayList<String>();

Upvotes: 9

Nikhil Sahu
Nikhil Sahu

Reputation: 2621

What @fge wrote is the correct way. However make sure you don't initialize them in a single line like:

mm = kk = new ArrayList<String>();

as this would lead to both the lists pointing to the same arraylist object and would mess up both the lists.

This single line initialization can be done for primitive data types but not for reference data types.

Upvotes: 0

Robin
Robin

Reputation: 36601

You can declare them in the same line, but you cannot initialize them. So

List<String> mm,kk;

is possible but then you still have to initialize them

mm = new ArrayList<String>();
kk = new ArrayList<String>();

Upvotes: 0

amit
amit

Reputation: 178421

Short answer: yes, you can declare 2 variables in the same expression. List<String> mm,kk; is declaring two lists.

Note that the operation kk = new ArrayList<String>(); is not a declaration, it is an assigment.

Upvotes: 7

Related Questions