条件运算符?(conditional Operator ? : type evaluation)

编程入门 行业动态 更新时间:2024-10-28 14:35:43
条件运算符?(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" }

我读了http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25,但仍然无法理解为什么它在eclipse中给出了编译错误

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只允许在需要语句的地方进行赋值和调用,而不是任意表达式。

从JLS第14.8节:

某些类型的表达式可以用分号跟随它们作为语句:

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

三元运算符( ConditionalExpression )不在该列表中,因此除了作为较大表达式或初始值设定项的一部分之外,它不会出现。

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.

更多推荐

本文发布于:2023-07-25 10:51:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1260081.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:运算符   条件   conditional   evaluation   type

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!