Replacing an if statement with a clause

Just for fun, I tried replacing:

if (set1.add(x) == false)
{
    set2.add(x);
}

with:

set1.add(x) || set2.add(x);

However, Eclipse complains:

Syntax error on token "||", invalid AssignmentOperator
The left-hand side of an assignment must be a variable

Can someone highlight these error messages? They make no sense to me.

+3
source share
5 answers

There are several answers at the moment, but I agree with the Bohemian answer that the simplest simplification is (although it does not use ||):

if ( !set1.add(x) ) set2.add(x);

. , , . exp1 || exp2 - , , , . 14.8. , , , :

14.8.

.

ExpressionStatement:
    StatementExpression ;

StatementExpression:
    Assignment
    PreIncrementExpression
    PreDecrementExpression
    PostIncrementExpression
    PostDecrementExpression
    MethodInvocation
    ClassInstanceCreationExpression

; , .

, , , , . , . ( ):

C ++ Java , . , Java "cast to void" - void - :

(void)... ;  // incorrect!

. , Java void, . , (§15.26) (§14.4).

, Reik Val :

boolean temp = set1.add(x) || set2.add(x);
+3

@qqilihq ,

boolean temp = set1.add(x) || set2.add(x);

:

if(set1.add(x) || set2.add(x));
+7

java-, , :

Assignment expressions
Any use of ++ or --
Method invocations
Object creation expressions

, , statement it a expression. . , .

+5

:

if (!set1.add(x))
    set2.add(x);
+1

boolean temp = set1.add(x) || set2.add(x);

and any change is dangerous. You are unlikely to ever know what is happening there. Note that the correct expression is NOT evaludated if the first expression true. That is, an attempt to add it to set2 will be executed only if it is not already contained in set1.

EDIT: Now, after reading the question again, it seems like this is exactly what you intended. Therefore, I believe that Anser fooobar.com/questions/2109405 / ... from Mustafa Genç matters here

You should usually write clearly what you want to do

boolean wasNotContainedInSet1 = set1.add(x);    
boolean wasNotContainedInSet2 = set2.add(x);    
boolean wasNotContainedInAnySet = 
    wasNotContainedInSet1 | wasNotContainedInSet2;

or

boolean wasNotContainedInSet1 = set1.add(x);    
if (!wasNotContainedInSet1) {
    set2.add(x);    
}

or something else...

0
source

All Articles