int
compareTo(E o)
比较此枚举与指定对象的顺序。ide
Class<E>
getDeclaringClass()
返回与此枚举常量的枚举类型相对应的 Class 对象。this
String
name()
返回此枚举常量的名称,在其枚举声明中对其进行声明。spa
int
ordinal()
返回枚举常量的序数(它在枚举声明中的位置,其中初始常量序数为零)。code
String
toString()
对象
返回枚举常量的名称,它包含在声明中。get
static
<T extends Enum<T>> T
valueOf(Class<T> enumType, String name)
返回带指定名称的指定枚举类型的枚举常量。class
package test; public class EnumTest { public enum Color { RED(255, 0, 0), BLUE(0, 0, 255), BLACK(0, 0, 0), YELLOW(255, 255, 0), GREEN(0, 255, 0); // 构造枚举值,好比RED(255,0,0) private Color(int rv, int gv, int bv) { this.redValue = rv; this.greenValue = gv; this.blueValue = bv; } private int redValue; // 自定义数据域,private为了封装。 private int greenValue; private int blueValue; public static final Color[] values=Color.values(); public static Color valueOf(int i) { return values[i]; } public String toString() { // 覆盖了父类Enum的toString() return super.toString() + "(" + redValue + "," + greenValue + "," + blueValue + ")"; } } public enum ColorType{ Red(Color.RED), Blue(Color.BLUE), Black(Color.BLACK), Yellow(Color.YELLOW), Green(Color.GREEN); private Color colorId; private ColorType(Color colorId) { this.colorId=colorId; } public static ColorType[] a=ColorType.values(); public static ColorType valueOf(int i) { return a[i]; } public String toString() { return super.toString()+"-------------->"+colorId.toString(); } } public static void main(String args[]) { // Color colors=new Color(100,200,300); //wrong Color color = Color.RED; Color colorYellow=Color.YELLOW; System.out.println(color); // 调用了toString()方法 System.out.println(color.ordinal()); System.out.println(color.compareTo(colorYellow)); //返回的是两个枚举值的顺序之差 System.out.println(Color.valueOf("BLUE")); System.out.println(Color.valueOf(1)); //重写valueOf方法 System.out.println(ColorType.valueOf(2).toString()); } }
运行结果:test
RED(255,0,0) 0 -3 BLUE(0,0,255) BLUE(0,0,255) Black-------------->BLACK(0,0,0)
自定义方法:方法
package test; public class EnumTest3 { public enum EnumTest { MON(1), TUE(2), WED(3), THU(4), FRI(5), SAT(6) { @Override public boolean isRest() { return true; } }, SUN(0) { @Override public boolean isRest() { return true; } }; private int value; private EnumTest(int value) { this.value = value; } public int getValue() { return value; } public boolean isRest() { return false; } } public static void main(String[] args) { System.out.println("EnumTest.FRI 的 value = " + EnumTest.SAT.isRest()); } }
输出结果:im
EnumTest.FRI 的 value = true