Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize arrays using ternary operator

i tried something like this:


boolean funkyBoolean = true;
int array[] = funkyBoolean ? {1,2,3} : {4,5,6};

But this code won't even compile. Is there any explanation for this? isn't funkyBoolean ? {1,2,3} : {4,5,6} a valid expression? thank's in advance!

like image 486
marcosbeirigo Avatar asked Nov 25 '09 13:11

marcosbeirigo


1 Answers

You can only use the {1, 2, 3} syntax in very limited situations, and this isn't one of them. Try this:

int array[] = funkyBoolean ? new int[]{1,2,3} : new int[]{4,5,6};

By the way, good Java style is to write the declaration as:

int[] array = ...

EDIT: For the record, the reason that {1, 2, 3} is so restricted is that its type is ambiguous. In theory it could be an array of integers, longs, floats, etc. Besides, the Java grammar as defined by the JLS forbids it, so that is that.

like image 77
Stephen C Avatar answered Sep 18 '22 01:09

Stephen C