1. Java枚举示例
5 a; ~% F: h, G/ O: x
- package com.mkyong.java
-
- public enum Language {
- JAVA,
- PYTHON,
- NODE,
- NET,
- RUBY
- }
5 _) M3 S, Q& t+ H4 M
2.与==比较
; S7 Q s5 @7 G+ `4 \( |* Q4 P W 将枚举值与==运算符进行比较的示例。- 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");
- }
-
- }
-
- }
: O- G1 W4 l( a3 V0 w
输出量:Welcome Java
, h9 y& T3 z" G# G3.与开关比较9 D& {1 w5 D. G( A) U9 W$ u6 F$ a
另外,您可以将枚举值与switch语句进行比较。
% `5 s$ w- v+ V' h a# G* j- h! }- 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;
- }
- }
- }
$ e0 y r+ W, i" I3 J 输出量:Welcome Python6 R- j' T/ P4 g+ C7 }1 o/ l: X! M
|