Java 三元运算符 (? :) doesn't work; second or third operand return boolean

标签 java ternary-operator

有人可以告诉我为什么三元运算符的使用不正确吗?操作数 2 和 3 返回一个 boolean 值。

public class Something {
...
private static final double REFERENCE_FRAME_MID_X = 0;
private static final double REFERENCE_FRAME_MID_Y = 0;

private boolean findInsideOrOutsideGeneralEllipse(Point2D destCirclePos) {
    List<Boolean> returnValue = new ArrayList<>();
    Point2D referenceFrameCenter = new Point2D.Double(REFERENCE_FRAME_MID_X, REFERENCE_FRAME_MID_Y);
    Ellipse2D insideAreaEllipse2D = getEllipse2D(referenceFrameCenter.getX(), referenceFrameCenter.getY(),
                                                    destCirclePos.distance(referenceFrameCenter));

    // doesn't work
    insideAreaEllipse2D.contains(destCirclePos) ? returnValue.add(true) : returnValue.add(false);

    // works
    if (insideAreaEllipse2D.contains(destCirclePos)) {
        returnValue.add(true);
    } else {
        returnValue.add(false);
    }
}
...
}

最佳答案

Java 三元运算条件的用法应该如下所示

result = testCondition ? value1 : value2

这是java语言规范。

Equality, Relational, and Conditional Operators

In the following example, this operator should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result

关于Java 三元运算符 (? :) doesn't work; second or third operand return boolean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19010399/

相关文章:

java - 为什么Hashtable/ConcurrentHashMap的put方法需要锁?

java - 每个事务后 Hibernate 提交会导致速度变慢

java - 使用新版本运行时 (8.x) 的旧版本 Java.exe (7.1) 的含义

javascript - 制作一个带有 3 个参数的函数范围,有异常(exception)吗?

javascript - 如何在映射时跳过 null? JSX

javascript - 如果 Ramda ifElse 抽象了一个三元运算,那么它是一个有效的模式吗

javascript - JS ECMA6 - 用于向后兼容的三元运算符

java - Hibernate 4.3 索引注释

java - 三元运算符如何评估结果数据类型?

java - Apache Felix 与 Pax Web War Extender 启动 bundle 时出错