博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JAVA中enum的常见用法
阅读量:4316 次
发布时间:2019-06-06

本文共 1503 字,大约阅读时间需要 5 分钟。

JAVA中enum的常见用法包括:定义并添加方法、switch、遍历、EnumSet、EnumMap

1.定义enum并添加或覆盖方法

 

public Interface Behaviour{        void print();}enum Color implements Behaviour{	RED("red",1),GREEN("green",2),BLUE("blue",3);//注意这里有个分号		private String name;	private int index;	private Color(String name,int index){		this.name = name;		this.index = index;	}	public static String getName(int index){		for(Color color : Color.values()){			if(color.index == index)				return color.name;		}		return null;	}	public String toString(){//覆写toString()方法		return this.index + ":" + this.name; 	}        public String getInfo(){                return this.name;        }}

 

①这个Color枚举类是个final class,不能被继承,它本身是继承自Enum;

②这些枚举值是Color对象,而且是static final修饰的;

③valueOf(String)方法,返回带指定名称的指定枚举类型的枚举常量。

2.switch和enum的遍历

 

public static void main(String[] args) {		Color c =  Color.valueOf("BLUE");	switch(c){	case RED:		System.out.println(c);	case BLUE:		System.out.println(c);	}		for(Color color : Color.values()){		System.out.println(color.toString());	}}

switch其实是支持int基本类型,而因为byte,short,char可以向上转换为int,所以switch也支持它们,但long因为转换int会截断便不能支持。

 

3.EnumSet和EnumMap的用法

 

public static void main(String[] args) {	EnumSet
es = EnumSet.allOf(Color.class); for(Color color : es){ System.out.println(color); } EnumMap
colorMap = new EnumMap
(Color.class); colorMap.put(Color.RED, "red"); colorMap.put(Color.GREEN, "green");}

EnumMap的key是enum,value是任何其他Object对象。

 

参考资料:

 

转载于:https://www.cnblogs.com/dyllove98/p/3190216.html

你可能感兴趣的文章
C#实现office文档转换为PDF或xps
查看>>
关于MVC整理
查看>>
etcd使用经历
查看>>
力扣 报错 runtime error: load of null pointer of type 'const int'
查看>>
angular_directive的controllerAs
查看>>
Ubuntu下修改为永久DNS的方法
查看>>
BabeLua常见问题
查看>>
Javascript 中 == 和 === 区别是什么?
查看>>
conductor 事件处理程序
查看>>
C#设计模式——小结
查看>>
文件修改等
查看>>
阅读后提问
查看>>
SQL 基本(Head First)
查看>>
由函数clock想到的
查看>>
SQL Server常用语句
查看>>
卡尔曼滤波器 算法
查看>>
工作中新接触的问题
查看>>
linux内存和swap
查看>>
怎样早期发现冠心病
查看>>
同时执行多个$.getJSON() 出现数据混乱的问题的解决
查看>>