简体   繁体   中英

conditional Operator ? : type evaluation

void method(Set<String> whiteListProviders){

        HashSet<String> hashedWhitelistedProviders;

        HashSet<String> fdsfh = (hashedWhitelistedProviders = (HashSet<String>) whitelistedProviders);

        HashSet<String> ghjk = (hashedWhitelistedProviders = new HashSet<String>(whitelistedProviders));

        HashSet<String> gh4jk = true ? fdsfh : ghjk; //compiles

        true?fdsfh:ghjk; //gives error "Type mismatch: cannot convert from HashSet<String> to boolean" 




}

I read http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25 but still couldn't understand why it is giving compilation error in eclipse

Java only allows assignments and calls where a statement is expected, not arbitrary expressions.

From section 14.8 of the JLS :

Certain kinds of expressions may be used as statements by following them with semicolons:

 ExpressionStatement: StatementExpression ; StatementExpression: Assignment PreIncrementExpression PreDecrementExpression PostIncrementExpression PostDecrementExpression MethodInvocation ClassInstanceCreationExpression 

The ternary operator ( ConditionalExpression ) is not on that list, so it can't appear except as part of a larger expression or initializer.

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