条件运算符?:类型评估

Pus*_*raj 1 java conditional

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" 




}
Run Code Online (Sandbox Code Playgroud)

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

Mik*_*uel 5

Java只允许在需要语句的地方进行赋值和调用,而不是任意表达式.

JLS14.8节:

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

ExpressionStatement:
        StatementExpression ;

StatementExpression:
        Assignment
        PreIncrementExpression
        PreDecrementExpression
        PostIncrementExpression
        PostDecrementExpression
        MethodInvocation
        ClassInstanceCreationExpression
Run Code Online (Sandbox Code Playgroud)

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