1. Java枚举示例* ]' z; Z. f& A$ O
- package com.mkyong.java
-
- public enum Language {
- JAVA,
- PYTHON,
- NODE,
- NET,
- RUBY
- }
. ]1 t& ] S/ v
2.与==比较5 n+ X* ?7 q% r8 D9 \
将枚举值与==运算符进行比较的示例。- 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");
- }
-
- }
-
- }
3 e( _! h3 P, m( f W1 a! A 输出量:Welcome Java* P4 S" P& X% }4 c6 ?
3.与开关比较
6 I9 G) W! u2 a# k 另外,您可以将枚举值与switch语句进行比较。( ?5 M( B/ }, D+ m! c7 d
- package 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;
- }
- }
- }
# a! f6 Y! s& p& R( I 输出量:Welcome Python
8 l! H9 D1 |% k+ t7 O& @ |