我读了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.
更多推荐
发布评论