SWITCH
switch语句就是根据匹配的值,执行不同的操作
ENUM
使用enum绑定值与操作的关系
public enum ComputeEnum {
PLUS("+") {
@Override
public int apply(int x, int y) {
return x + y;
}
},
MINUS("-") {
@Override
public int apply(int x, int y) {
return x - y;
}
};
public String getName() {
return name;
}
String name;
ComputeEnum(String name) {
this.name = name;
}
public abstract int apply(int x, int y);
}
测试代码
public class TestEnum {
public static void main(String[] args) {
TestData testData = new TestData(ComputeEnum.PLUS, 1, 1);
TestData testData1 = new TestData(ComputeEnum.MINUS, 1, 1);
TestData testData2 = new TestData(ComputeEnum.PLUS, 1, 1);
List<TestData> list = new ArrayList<>();
list.add(testData);
list.add(testData1);
list.add(testData2);
list.stream().forEach(x -> {
x.getComputeEnum().apply(x.getNum(), x.getCount());
});
}
}
@Data
class TestData {
ComputeEnum computeEnum;
int num;
int count;
}