2012-03-13 110 views
5

假設有一個ENUM枚舉作爲運算

enum Operations { 
    ADD, 
    SUBTRACT, 
    MULTIPLY 
} 

我想用這個枚舉兩個數字(比如5和3),得到輸出添加爲8 或 我想用這個枚舉減去兩個數字(比如9和3),得到輸出爲6

問:

  • 這可能嗎?
  • 如果是,那麼要對此枚舉進行哪些修改?

回答

17

enum S可有抽象方法,每個成員都可以有不同的實現它。

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); 
} 

將允許你這樣做

Operations op = ...; 
double result = op.apply(3, 5); 
+2

很好的答案,+1。 – Perception 2012-03-13 03:54:39

4

您可以使用枚舉值開關:

switch (operator) { 
case ADD: 
    ret = a + b; 
    break; 
case SUBTRACT: 
    ret = a - b; 
    break; 
case MULTIPLY: 
    ret = a * b; 
    break; 
} 
1

您應該使用枚舉作爲標誌進行什麼操作:

public int computeOperation(int leftOperand, Operation op, int rightOperand) { 
    switch(op) { 
     case ADD: 
      return leftOperand + rightOperand; 
     case SUBTRACT: 
      return leftOperand - rightOperand; 
     case MULTIPLY: 
      return leftOperand * rightOperand; 
    } 

    return null; 

既然你回來了每一種情況下,你不需要擔心通過。

4

如何使用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); 
    } 
}