Rhythmk 一步一步学 JAVA (20) JAVA enum常用方法
时间:2014-04-28 07:01:10
收藏:0
阅读:575
JAVA 枚举定义常用方法:
1、static Enum valueOf(Class enum,String name)
返回指定name的枚举类型
2、Static Enum values[]
返回枚举常量集合
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96 |
package
com.rhythmk.filedemo; import java.util.Scanner; public class enum_demo { public
static void main(String[] args) { System.out.println( "------------------------1-----------------------------" ); //1、获取枚举对象所有枚举类型 Size[] sizeArr=Size.values(); for
(Size size : sizeArr) { System.out.println(size.toString()); } System.out.println( "------------------------2-----------------------------" ); // 2、通过 Enum 的 Indexof(EnumType,name) 返回于name同名的枚举属性 Scanner sc= new
Scanner(System.in); System.out.println( "请输入Size属性[SMALL,BIG,LARGE]" ); String sInput=sc.next(); Size smallSize=Size.SMALL; Size eInput=Size.valueOf(Size. class ,sInput); if (eInput==smallSize) { System.out.println( "True,‘枚举对象为:‘" +eInput); } else { System.out.println( "False" ); } System.out.println( "------------------------3-----------------------------" ); // 3、调用枚举定义方法 String sizeShow=Size.SMALL.Show(); System.out.println(sizeShow); Size bigLarge= Size.BIGLARGE; System.out.println( "------------------------4-----------------------------" ); // 4、调用枚举自定义方法 String sblogsShow=Blog.RHYTHMK.Show(); System.out.println(sblogsShow); } } enum Size { SMALL, BIG, LARGE, BIGLARGE( "BIGLARGE" ); private
Size() {} private
Size(String str) { System.out.println( "Size被创建,传入值为:" +str); } public
String Show() { return
"调用枚举定义方法回传值" ; } } enum Blog { CNBLOGS( "博客园" ), CSDN( "CSDN博客" ), RHYTHMK( "本博客" ); private
Blog(String str) { this ._show=str; } private
String _show; private
String getShow() { return
_show; } public
String Show() { return
"当前选择博客为:" +getShow(); } } |
输出:
------------------------1-----------------------------
Size被创建,传入值为:BIGLARGE
SMALL
BIG
LARGE
BIGLARGE
------------------------2-----------------------------
请输入Size属性[SMALL,BIG,LARGE]
SMALL
True,‘枚举对象为:‘SMALL
------------------------3-----------------------------
调用枚举定义方法回传值
------------------------4-----------------------------
当前选择博客为:本博客
评论(0)