枚举
一,枚举的定义
从技术上讲,枚举是一个类,可以有构造方法和方法。如果有构造方法,那必须是私有的。如果一个enum定义了枚举值之外的其他内容,枚举值必须在其他内容之前定义,并且最后的枚举值用一个分号结束。
二,枚举的使用
1,定义常量:我们一般定义常量通过(private static final …)或者接口(interface),而枚举也可以定义常量。
public class EnumTest { //定义常量的第一种方式 private static final String red = "红"; private static final String blue = "蓝"; private static final String yellow = "黄";
//定义常量的第二种方式 public interface con { String red = "红"; String blue = "蓝"; String yellow = "黄"; }
//定义常量的第三种方式 public enum color { 红, 蓝, 黄; }
public static void main(String[] args) { System.out.println(red); System.out.println(con.red); System.out.println(color.红); } } |
2,switch,自从jdk1.6后Switch语句中可以添加枚举类型
、 public enum Color { red, blue, yellow; }
public static void main(String[] args) { System.out.println(red); System.out.println(con.red); System.out.println(Color.red); Color color = Color.red; switch(color){ case red: System.out.println("红色"); break; case blue: System.out.println("蓝色"); break; case yellow: System.out.println("黄色"); break; } } |
3,枚举是类类型
Java中枚举是类类型,虽然不能使用new关键字来实例化枚举,但是枚举却有和其他类相同的功能,可以为枚举提供构造函数、实例变量和方法,甚至可以实现接口
a,需要理解的是:每个枚举变量都是所属枚举类型的对象。因此,如果为枚举定义了构造函数,那么当创建每个枚举常量时都会调用该构造函数
b,为枚举 Color提供一个实例变量 value、一个返回value值的方法、两个不同的构造函数。
c,对于每一个枚举常量,指定要调用的构造函数的方法是通过每个常量后面的圆括号中来加以指定
public enum Color { red("red", "红色"), blue("blue", "蓝色"), yellow("yellow", "黄色"); private String value; private String desc;
Color(String value, String desc) { this.value = value; this.desc = desc; }
public String getDesc() { return desc; }
public String getValue() { return value; } public static String getDescription(String value){ Color[] values = Color.values(); for (int i = 0; i < values.length; i++) { Color value1 = values[i]; if(value1.getDesc().equals(value)){ return value1.getDesc(); } // System.out.println("yhl"+value1); } return "没有对应的颜色"; } }
public static void main(String[] args) { System.out.println(Color.getDescription("色"));
} |
4,枚举的一些方法
a,values():values() 方法返回一个包含枚举常量列表的数组
b,valueOf(String):方法返回与传递的字符串参数相对应的枚举常量
c,ordinal():方法返回枚举常量在常量列表中位置的值,这称为枚举常量的序数值
d,compareTo(Enum):方法用于比较相同类型的两个枚举常量的序数值
e,equals(Enum):用于比较两个对象的相等性,只有两个对象都引用同一个枚举中相同的常量时,返回值才为 true
5,枚举实现接口
public interface Command { void execute(); } public enum Color implements Command { RED, GREEN, BLUE;
@Override public void execute() { switch (this) { case RED: System.out.println("选中的是红色"); break; case GREEN: System.out.println("选中的是绿色"); break; case BLUE: System.out.println("选中的是蓝色"); break; } } } //第二种创建方式 public enum Color implements Command {
RED { public void execute() { System.out.println("选中的是红色"); } }, GREEN { public void execute() { System.out.println("选中的是绿色"); } }, BLUE { public void execute() { System.out.println("选中的是蓝色"); } }; } |