1. Java枚举示例
, P+ [8 T1 w) s4 w. wpackage com.mkyong.java
public enum Language {
JAVA,
PYTHON,
NODE,
NET,
RUBY
}
( \/ d1 E3 Z. N G8 m/ f2.与==比较( D- |5 J0 c9 L" V6 l$ x4 [ a" `; A
将枚举值与==运算符进行比较的示例。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");
}
}
}
& f/ P5 f0 h8 u2 h$ c( @ 输出量:Welcome Java4 c" P5 j0 R m6 {# C6 {
3.与开关比较
p* `: i0 K# x& q; }0 b" V$ ? 另外,您可以将枚举值与switch语句进行比较。
2 `/ e. q, _3 k8 zpackage 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;
}
}
} & ^3 s/ D: f( j5 D5 `
输出量:Welcome Python( s# y( L5 c. N5 C% c. c
|