简体   繁体   English

条件运算符? :类型评估

[英]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 我读了http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25,但仍然不明白为什么它会在Eclipse中产生编译错误

Java only allows assignments and calls where a statement is expected, not arbitrary expressions. Java仅允许在需要语句的地方进行赋值和调用,而不是任意表达式。

From section 14.8 of the JLS : JLS的14.8节开始:

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. 三元运算符( ConditionalExpression )不在该列表上,因此它不能出现,除非作为较大的表达式或初始化程序的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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