枚举
枚举常量的修饰符会省略。实际的修饰符是 final static。final表示不可以被继承,static表示是类成员常量。
枚举的好处:
1、类型安全
2、紧凑有效的数据定义
3、可以和程序其他部分完美交互
4、运行效率高
1、定义枚举类
public enum Constants_01 {
//定义枚举类成员常量
CONSTANTS_A,
CONSTANTS_B,
CONSTANTS_C;
}
2、展示枚举成员常量
public class ShowEnum_02 {
enum Constants{
Constants_A,Constants_B
}
public static void main(String[] args) {
//Constants.values() 获取所有枚举类所有的成员,并且以数组返回
for (int i = 0; i < Constants.values().length; i++) {
System.out.println("枚举类型的成员变量:"+Constants.values()[i]);
}
}
}
3、枚举类型之间的比较(比较的枚举常量的位置)
public class EnumMethodTest_03 {
//定义比较枚举类型方法,参数类型为枚举
public static void compare(ShowEnum_02.Constants constants){
for (int i = 0; i < ShowEnum_02.Constants.values().length; i++) {
System.out.println(constants+"与"+ShowEnum_02.Constants.values()[i]+"的比较结果为:"+constants.compareTo(ShowEnum_02.Constants.values()[i]));
}
}
public static void main(String[] args) {
//在同一个类中,可以互相调用方法,又因为是static,所以可以直接用方法名
compare(ShowEnum_02.Constants.valueOf("Constants_A"));
}
}
4、获取枚举类型在索引的位置
public class EnumIndexTest_04 {
enum Constants{
//将常量放置在枚举类型
Constant_A,Constant_B,Constant_C
}
public static void main(String[] args) {
for (int i = 0; i < Constants.values().length; i++) {
System.out.println(Constants.values()[i]+"在枚举类型中索引位置为:"+Constants.values()[i].ordinal());
}
}
}
4、获取枚举类型在索引的位置
public class EnumStructTest_05 {
enum Constants{
Constant_A("我是枚举成员A"),
Constant_B("我是枚举成员B"),
Constant_C("我是枚举成员C"),
Constant_D(3);
private String description;
private int i=4;
private Constants(){
}
private Constants(String description){
this.description=description;
}
private Constants(int i){
this.i=this.i+i;
}
public String getDescription() {
return description;
}
public int getI() {
return this.i;
}
}
public static void main(String[] args) {
for (int i = 0; i < Constants.values().length; i++) {
System.out.println(Constants.values()[i]+"调用getDescription()方法为:"+Constants.values()[i].getDescription());
}
System.out.println(Constants.valueOf("Constant_D")+"调用getI()方法为"+Constants.valueOf("Constant_D").getI());
}
}
5、枚举练习
//定义一个枚举类,使用switch语句获取枚举类型的值
public class Practice_01 {
enum Constant{
constant_A,
constant_B,
constant_C
}
public void doit(Constant c){
switch (c){
case constant_A:
System.out.println("A");
break;
case constant_B:
System.out.println("B");
break;
case constant_C:
System.out.println("C");
break;
}
}
public static void main(String[] args) {
new Practice_01().doit(Constant.constant_C);
}
}
6、总结
个人觉得枚举很安全,在大家觉得使用某个类的成员属性是固定的话,但是又不想要去处理很多异常输入的情况,就固定为枚举类,使用的时候就只能使用枚举类中定义的成员属性去匹配内容吗,这样可以减少很多if语句嘞。