Ternary comparison if in Java
•
Java
Why is it incorrect to use such triples, because it is correct to use if?
//Error when using as ternary Character.isDigit(myDto.getNamestr().charAt(0)) ? digitArrayList.add(myDto) : charArrayList.add(myDto); //OK when used as if ... else char c = myDto.getNamestr().charAt(0); if(Character.isDigit(c)) { digitArrayList.add(myDto); } else { charArrayList.add(myDto); }
Solution
Ternary conditions are not allowed as stand - alone statements Only certain expressions are allowed as stand - alone statements, such as assignments or method calls
JLS classifies expressions that are allowed to be independent statements as STATEMENTEXPRESSION:
In any case, there are several ambiguous ways to use triples here:
// statement is an assignment boolean ignored = Character.isDigit(...) ? digitArrayList.add(myDto) : charArrayList.add(myDto); // statement is a method invocation (Character.isDigit(...) ? digitArrayList : charArrayList) .add(myDto);
But I don't recommend using them. They're just curiosity It's easier to use if... Else
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码