枚举为算术运算

Lea*_*ner 5 java core

假设有一个ENUM

enum Operations { 
  ADD, 
  SUBTRACT, 
  MULTIPLY
}
Run Code Online (Sandbox Code Playgroud)

我想使用这个枚举添加两个数字(比如5和3)并将输出设为8或者我想使用这个枚举减去两个数字(比如说9和3)并得到输出为6

题:

  • 这可能吗?
  • 如果是,那么对这个枚举的修改是什么?

Mik*_*uel 20

enums可以有抽象方法,每个成员可以以不同方式实现它.

enum Operations {
  ADD {
    public double apply(double a, double b) { return a + b; }
  }, 
  SUBTRACT {
    public double apply(double a, double b) { return a - b; }
  }, 
  MULTIPLY {
    public double apply(double a, double b) { return a * b; }
  }, 
  ;

  public abstract double apply(double a, double b);
}
Run Code Online (Sandbox Code Playgroud)

会允许你这样做

Operations op = ...;
double result = op.apply(3, 5);
Run Code Online (Sandbox Code Playgroud)


Ins*_*Bot 5

如何使用JAVA 8功能:

enum Operation implements DoubleBinaryOperator {
    PLUS    ("+", (l, r) -> l + r),
    MINUS   ("-", (l, r) -> l - r),
    MULTIPLY("*", (l, r) -> l * r),
    DIVIDE  ("/", (l, r) -> l / r);

    private final String symbol;
    private final DoubleBinaryOperator binaryOperator;

    private Operation(final String symbol, final DoubleBinaryOperator binaryOperator) {
        this.symbol = symbol;
        this.binaryOperator = binaryOperator;
    }

    public String getSymbol() {
        return symbol;
    }

    @Override
    public double applyAsDouble(final double left, final double right) {
        return binaryOperator.applyAsDouble(left, right);
    }
}
Run Code Online (Sandbox Code Playgroud)