http://c.biancheng.net/cpp/ 读后整理
public enum Color{
RED("红色",1),GREEN("绿色",2),WHITE("白色",3),YELLOW("黄色",4);
//以上是枚举的成员(个人理解为类的实例),必须先定义,而且使用分号结束
//成员变量,可以没有,成员也就没有'(name,index)',也就不需要带参数的构造函数
private String name;
private int index;
//构造方法
private Color(String name,int index){
this.name=name;
this.index=index;
}
//覆盖方法,默认返回的是成员(实例)名,如RED
@Override
public String toString(){
return this.index+"-"+this.name;
}
//成员方法
public String getColor(){
return name;
}
}
调用:
类名 .成员名/实例名.成员变量/方法
Color.RED.name
Color.RED.index
Color.RED.getColor()
存储时是将成员/实例存入的。
两个枚举实例比较用equals()方法:
/**
* Returns true if the specified object is equal to this
* enum constant.
*
* @param other the object to be compared for equality with this object.
* @return true if the specified object is equal to this
* enum constant.
*/
public final boolean equals(Object other) {
return this==other;
}
枚举类的常用方法
方法名称 | 描述 |
---|---|
values() | 以数组形式返回枚举类型的所有成员,类名.values()[index]获取某个成员 |
valueOf(String s) | 将普通字符串转换为枚举实例 |
compareTo() | 比较两个枚举成员在定义时的顺序 |
ordinal() | 获取枚举成员的索引位置index,索引从0起,与上面例子中成员属性index不同 |
EnumMap<key,value>
使用数组来存放与枚举类型对应的值,使得 EnumMap 的效率非常高。
可以直接获取数组下标索引并访问到元素
EnumMap中的 key是enum类型,而 value 则可以是任意类型
EnumSet 类
要求放入它的枚举常量必须属于同一枚举类型,保证集合中的元素不重复
提供了许多工厂方法以便于初始化
方法名称 | 描述 |
---|---|
allOf(Class element type) | 创建一个包含指定枚举类型中所有枚举成员的 EnumSet 对象 |
copyOf(EnumSet s) | 创建一个与指定 EnumSet 对象 s 相同的枚举类型 EnumSet 对象,并与 s 包含相同的枚举成员 |
noneOf(<Class elementType) | 创建指定枚举类型的空 EnumSet 对象 |
of(E first,e…rest) | 创建包含指定枚举成员的 EnumSet 对象 |
range(E from ,E to) | 创建一个 EnumSet 对象,该对象包含了from 到 to 之间的所有枚举成员 |
complementOf(EnumSet s) | 创建一个与指定 EnumSet 对象 s 相同的枚举类型 EnumSet 对象,并包含所有 s 中未包含的枚举成员 |