JAVA 枚举的简单应用
程序员文章站
2022-06-16 16:54:30
...
public class Test {
public static void main(String[] args) {
for (Education e : Education.values()) {
System.out.println("Name : " + e.getName() + " | Value : "
+ e.getValue());
}
System.out.println(Education.Shuoshi.getName());
System.out.println(Education.Benke.getValue());
System.out.println("=================================================");
double x = 5;
double y = 10;
for (Operation op : Operation.values()) {
System.out.println(x + op.toString() + y + " = " + op.apply(x, y));
}
}
}
enum Education {
Boshi("博士", 1), Shuoshi("硕士", 2), Benke("本科", 3), Gaozhong("高中", 4);
private String name;
private int value;
private Education(String name, int value) {
this.name = name;
this.value = value;
}
public String getName() {
return this.name;
}
public int getValue() {
return this.value;
}
}
enum Operation {
PLUS("+") {
@Override
double apply(double x, double y) {
return x + y;
}
},
MINUS("-") {
@Override
double apply(double x, double y) {
return x - y;
}
},
TIMES("*") {
@Override
double apply(double x, double y) {
return x * y;
}
},
DIVIDE("/") {
@Override
double apply(double x, double y) {
return x / y;
}
};
private String symbol;
private Operation(String symbol) {
this.symbol = symbol;
}
abstract double apply(double x, double y);
@Override
public String toString() {
return this.symbol;
}
}
输出结果:
Name : 博士 | Value : 1
Name : 硕士 | Value : 2
Name : 本科 | Value : 3
Name : 高中 | Value : 4
硕士
3
=================================================
5.0+10.0 = 15.0
5.0-10.0 = -5.0
5.0*10.0 = 50.0
5.0/10.0 = 0.5
[b]利用枚举实现java单例:包含一个元素的枚举:[/b]
enum Singleton{
INSTANCE;
public void doSomething(){
//...
}
}