JAVA 枚举定义常用方法:
1、static Enum valueOf(Class enum,String name)
返回指定name的枚举类型
2、Static Enum values[]
返回枚举常量集合
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-----------------------------
当前选择博客为:本博客