一些Java枚举示例以及如何使用它,没什么特别的,仅用于自参考。
注意
如果您的程序由一组固定的常数组成,请考虑Enum类型,例如一年中的季节,操作计算器,用户状态等。
1.基本枚举
UserStatus.java
public enum UserStatus {
PENDING,
ACTIVE,
INACTIVE,
DELETED;
}
Test.java
public class Test {
public static void main(String[] args) {
//ACTIVE
System.out.println(UserStatus.ACTIVE);
}
}
2.枚举+实例字段
WhoisRIR.java
public enum WhoisRIR {
ARIN("whois.arin.net"),
RIPE("whois.ripe.net"),
APNIC("whois.apnic.net"),
AFRINIC("whois.afrinic.net"),
LACNIC("whois.lacnic.net"),
JPNIC("whois.nic.ad.jp"),
KRNIC("whois.nic.or.kr"),
CNNIC("ipwhois.cnnic.cn"),
UNKNOWN("");
private String url;
WhoisRIR(String url) {
this.url = url;
}
public String url() {
return url;
}
}
Test.java
public class Test {
public static void main(String[] args) {
//whois.arin.net
System.out.println(WhoisRIR.ARIN.url());
}
}
3.枚举+方法+一些逻辑
Operation.java
public enum Operation {
PLUS,
MINUS,
TIMES,
DIVIDE;
double calculate(double x, double y) {
switch (this) {
case PLUS:
return x + y;
case MINUS:
return x - y;
case TIMES:
return x * y;
case DIVIDE:
return x / y;
default:
throw new AssertionError("Unknown operations " + this);
}
}
}
Test.java
public class Test {
public static void main(String[] args) {
double result = Operation.PLUS.calculate(1, 2);
System.out.println(result); //3.0
}
}
4.如何使用枚举
4.1循环一个Enum对象。
public class Test {
public static void main(String[] args) {
for (UserStatus status : UserStatus.values()) {
System.out.println(status);
}
}
}
输出量
PENDING ACTIVE INACTIVE DELETED
4.2要比较Enum值,请使用==
运算符。
public class Test {
public static void main(String[] args) {
WhoisRIR rir = WhoisRIR.APNIC;
if(rir == WhoisRIR.APNIC) {
System.out.println("This is APNIC : " + rir.url());
}
}
}
输出量
This is APNIC : whois.apnic.net
4.3开关盒。
public class Test {
public static void main(String[] args) {
WhoisRIR rir = WhoisRIR.RIPE;
switch (rir) {
case ARIN:
System.out.println("This is ARIN");
break;
case APNIC:
System.out.println("This is APNIC");
break;
case RIPE:
System.out.println("This is RIPE");
break;
default:
throw new AssertionError("Unknown RIR " + rir);
}
}
}
输出量
This is RIPE
4.2将String转换为Enum对象。
public class Test {
public static void main(String[] args) {
//enum valueOf + uppercase
Operation op = Operation.valueOf("times".toUpperCase());
System.out.println(op.calculate(10, 3));
}
}
输出量
30.0
做完了
参考文献
标签: 枚举