1. Java枚举示例
# z( S+ T8 [( l S# [( [ _7 wpackage com.mkyong.java
public enum Language {
JAVA,
PYTHON,
NODE,
NET,
RUBY
}
1 A) m- E+ d7 U. M, \+ D2.与==比较
, a2 D; O& z( Y* Z* n 将枚举值与==运算符进行比较的示例。package com.mkyong.java
public class Test {
public static void main(String[] args) {
// Covert string to enum
//Language enumObj = Language.valueOf("java".toUpperCase());
Language enumObj = Language.JAVA;
if (enumObj == Language.JAVA) {
System.out.println("Welcome Java");
} else if (enumObj == Language.NET) {
System.out.println("Welcome .Net");
} else if (enumObj == Language.NODE) {
System.out.println("Welcome Node JS");
} else if (enumObj == Language.PYTHON) {
System.out.println("Welcome Python");
} else if (enumObj == Language.RUBY) {
System.out.println("Welcome Ruby");
} else {
System.out.println("Hello World");
}
}
}
+ R; l$ e" j4 ~* M9 G0 q+ O 输出量:Welcome Java$ ?8 I+ N0 T; T5 c; D/ P4 M
3.与开关比较, ?- q9 `7 D" k! r* N
另外,您可以将枚举值与switch语句进行比较。
/ u# }4 m5 h; i |+ @. m9 jpackage com.mkyong.java
public class Test {
public static void main(String[] args) {
Language enumObj = Language.PYTHON;
switch (enumObj) {
case JAVA:
System.out.println("Welcome Java");
break;
case NET:
System.out.println("Welcome .Net");
break;
case NODE:
System.out.println("Welcome Node JS");
break;
case PYTHON:
System.out.println("Welcome Python");
break;
case RUBY:
System.out.println("Welcome Ruby");
break;
default:
System.out.println("Hello World");
break;
}
}
} 0 N# A$ |: A* K
输出量:Welcome Python h+ o* q: D) |. C. B7 V
|