先来看下java中Enum的使用方法:
Java中的Enum的使用与分析
从上文中我们可以看出:每个枚举就是一个静态枚举常量平时我们代码里更常用的是:
public static final int BLACK = 0xFF000000;
public static final int DKGRAY = 0xFF444444;
public static final int GRAY = 0xFF888888;
public static final int LTGRAY = 0xFFCCCCCC;
public static final int WHITE = 0xFFFFFFFF;
public static final int RED = 0xFFFF0000;
public static final int GREEN = 0xFF00FF00;
public static final int BLUE = 0xFF0000FF;
public static final int YELLOW = 0xFFFFFF00;
public static final int CYAN = 0xFF00FFFF;
public static final int MAGENTA = 0xFFFF00FF;
从功能上来说 静态常量 == Enum
不同:静态常量是个INT的基本类型
Enum是个对象集合
但是到底Enum的用途是什么?
1.使用的限制,避免错误的发生
静态常量可以是任何的INT
Enum只能是定义的几个对象,不需要进行错误检测的代码,边界检测
参考:
枚举类型入门
阶段总结:
当我们需要定义一些类似枚举类型静态常量时,可以考虑下用枚举来实现是否更方便。
实例:
/**
* 角色类型
*/
public enum ActorType {
/** 玩家 */
PLAYER,
/** 敌人 */
ENEMY,
/** 树 */
TREE,
/** 门 */
DOOR
;
public static ActorType valueOfByte(byte v) {
switch (v) {
case 0:
return PLAYER;
case 1:
return ENEMY;
case 2:
return TREE;
case 3:
return DOOR;
default:
throw new IllegalArgumentException();
}
}
public byte byteValue() {
switch (this) {
case PLAYER:
return 0;
case ENEMY:
return 1;
case TREE:
return 2;
case DOOR:
return 3;
default:
throw new IllegalArgumentException();
}
}
}
2012.5.9
项目中开始用enum
用途:自定义脚本中使用,
使用GuildArrowType.valueOf(mPara[5].toUpperCase())来读取脚本里枚举
有效避免脚本出错,或随意填写,并起到一定的注释作用(枚举变量名)
脚本:
// 菜单指示
TipSet(MENU, 0, 0, 50, 65, LU, 点击打开菜单)
枚举类
public enum GuildArrowType {
/** 上 */
U,
/** 右上 */
RU,
/** 右 */
R,
/** 右下 */
RD,
/** 下 */
D,
/** 左下 */
LD,
/** 左 */
L,
/** 左上 */
LU
}