假设有一个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)
如何使用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)
| 归档时间: |
|
| 查看次数: |
8152 次 |
| 最近记录: |