This article mainly introduces relevant information about the use of Java enumerations. I hope that through this article, everyone can master the use of enumerations. Friends in need can refer to
Java Enumerations Detailed explanation of how to use
Preface The flag and status in your code should be replaced by enumerations
Many people say that enumerations It is rarely used in actual development, or even not used at all. Because their code often looks like this:
public class Constant { /* * 以下几个变量表示英雄的状态 */ public final static int STATUS_WALKING = 0;//走 public final static int STATUS_RUNNINGING = 1;//跑 public final static int STATUS_ATTACKING = 2;//攻击 public final static int STATUS_DEFENDING = 3;//防御 public final static int STATUS_DEAD = 4;//挂了 /* * 以下几个变量表示英雄的等级 */ //此处略去N行代码 }
Then, they use this class like this:
hero.setStatus(Contant.STATUS_ATTACKING);
Well, then they said, "I rarely use enumerations in actual development"
Of course, they mean that they rarely use enumerations Take the Enum class.
However, what I want to say is that all the above codes should be implemented using Enum.
Why?
Because their code is completely based on trust in teammates, suppose a strange teammate comes and does this:
hero.setStatus(666);
Tell me, what will happen to the hero on the screen?
In short, if you often use such code in actual programming, it is time to learn Enum.
A preliminary study on enumerations Why use enumeration types
There are enumerations everywhere in life, including "natural enumerations", such as planets and weeks The number of days also includes the enumerations we designed, such as csdn tab labels, menus, etc.
There are generally two ways to express enumerations in Java code. One is the int enumeration, but the Enum enumeration. Of course, we all know that the Enum enumeration is provided by Java. True enumeration.
So, why do we use the Enum enumeration type? Let's first take a look at how we represented enumerations before Java 1.5 when there were no enumeration types.
Take the eight planets as an example. Each planet corresponds to an int value. We will probably write it like this
public class PlanetWithoutEnum { public static final int PLANET_MERCURY = 0; public static final int PLANET_VENUS = 1; public static final int PLANET_EARTH = 2; public static final int PLANET_MARS = 3; public static final int PLANET_JUPITER = 4; public static final int PLANET_SATURN = 5; public static final int PLANET_URANUS = 6; public static final int PLANET_NEPTUNE = 7; }
This is called int enumeration mode, of course you can also use String enumeration mode, no matter which method is used, this approach is very poor in terms of type safety and ease of use.
If the variable planet represents a planet, the user can assign this value to a value that is not in our enumeration value, such as planet = 9. Only God knows which planet this is; furthermore, it is difficult for us to calculate. Without knowing how many planets there are, it would be difficult for us to traverse the planets and so on.
Now we use enumerations to create our planets.
public enum Planet { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE; }
The above is the simplest enumeration. Let’s call it Planet 1.0. In this version of planet enumeration, we have implemented a function, which is any Variables of type Planet can be guaranteed by the compiler that any non-null object passed to the parameter must belong to one of these eight planets.
Then, we upgrade Planet. Java allows us to add any method to the enumeration type. Here is the code in the book. Let’s experience the enumeration’s constructor, public method, and enumeration by yourself. Give knowledge points such as traversal.
##
public enum Planet { MERCURY(3.302e+23, 2.439e6), VENUS(4.869e+24, 6.052e6), EARTH(5.975e+24,6.378e6), MARS(6.419e+23, 3.393e6), JUPITER(1.899e+27, 7.149e7), SATURN(5.685e+26, 6.027e7), URANUS(8.683e+25, 2.556e7), NEPTUNE(1.024e+26,2.477e7); private final double mass; // In kilograms private final double radius; // In meters private final double surfaceGravity; // In m / s^2 // Universal gravitational constant in m^3 / kg s^2 private static final double G = 6.67300E-11; // Constructor Planet(double mass, double radius) { this.mass = mass; this.radius = radius; surfaceGravity = G * mass / (radius * radius); } public double mass() { return mass; } public double radius() { return radius; } public double surfaceGravity() { return surfaceGravity; } public double surfaceWeight(double mass) { return mass * surfaceGravity; // F = ma } }
//注:这里对书中的代码做了微调 public class WeightTable { public static void main(String[] args) { printfWeightOnAllPlanets(8d); } public static void printfWeightOnAllPlanets(double earthWeight) { double mass = earthWeight / Planet.EARTH.surfaceGravity(); for (Planet p : Planet.values()) System.out.printf("Weight on %s is %f%n", p, p.surfaceWeight(mass)); } }Run WeightTable and the printed results are as follows:
Weight on MERCURY is 3.023254 Weight on VENUS is 7.240408 Weight on EARTH is 8.000000 Weight on MARS is 3.036832 Weight on JUPITER is 20.237436 Weight on SATURN is 8.524113 Weight on URANUS is 7.238844 Weight on NEPTUNE is 9.090108In this small program, we use the values() method of the enumeration. This method returns a collection of enumeration variables in the enumeration type, which is very practical. Enumeration Advanced Calculator Operator Enumeration Class
First of all, we can easily think of a method. In the public method, use switch to determine the enumeration type, and then perform different operations. The code is as follows:
public enum OperationUseSwitch { PLUS, MINUS, TIMES, pIDE; double apply(double x, double y) { switch (this) { case PLUS: return x + y; case MINUS: return x + y; case TIMES: return x + y; case pIDE: return x + y; } // 如果this不属于上面四种操作符,抛出异常 throw new AssertionError("Unknown operation: " + this); } }
This code does meet our needs, but it has two drawbacks.
First of all, we have to throw an exception at the end or add default to the switch, otherwise it will not compile. But obviously, the branch of the program will not enter the exception or default.
Secondly, this code is very fragile. If we add a new operation type but forget to add the corresponding processing logic in the switch, problems will occur when performing new operations.
Fortunately, Java enumerations provide a feature called constant-specific method implementation.
We only need to declare an abstract method in the enumeration type, and then override this method in each enumeration constant. The implementation is as follows:
public enum Operation { PLUS { double apply(double x, double y) { return x + y; } }, MINUS { double apply(double x, double y) { return x - y; } }, TIMES { double apply(double x, double y) { return x * y; } }, pIDE { double apply(double x, double y) { return x / y; } }; abstract double apply(double x, double y); }
In this way, we will never forget to add the corresponding processing logic after adding a new operator, because the compiler will prompt us that we must override the apply method.
However, this constant-specific method implementation has a disadvantage, that is, it is difficult for you to share code between enumeration constants.
Let’s take the enumeration of week
如果还是使用 特定于常量的方法实现,写出来的代码可能就是这样的:
public enum DayUseAbstractMethod { MONDAY { @Override void apply() { dealWithWeekDays();//伪代码 } }, TUESDAY { @Override void apply() { dealWithWeekDays();//伪代码 } }, WEDNESDAY { @Override void apply() { dealWithWeekDays();//伪代码 } }, THURSDAY { @Override void apply() { dealWithWeekDays();//伪代码 } }, FRIDAY { @Override void apply() { dealWithWeekDays();//伪代码 } }, SATURDAY { @Override void apply() { dealWithWeekEnds();//伪代码 } }, SUNDAY { @Override void apply() { dealWithWeekEnds();//伪代码 } }; abstract void apply(); }
很明显,我们这段代码里面有相当多的重复代码。
那么要怎么优化呢,我们不妨这样想,星期一星期二等等是一种枚举,那么工作日和休息日,难道不也是一种枚举吗,我们能不能给Day的构造函数传入一个工作日休息日的DayType枚举呢?这也就是书中给出的一种叫策略枚举 的方法,代码如下:
public enum Day { MONDAY(DayType.WEEKDAY), TUESDAY(DayType.WEEKDAY), WEDNESDAY( DayType.WEEKDAY), THURSDAY(DayType.WEEKDAY), FRIDAY(DayType.WEEKDAY), SATURDAY( DayType.WEEKDAY), SUNDAY(DayType.WEEKDAY); private final DayType dayType; Day(DayType daytype) { this.dayType = daytype; } void apply() { dayType.apply(); } private enum DayType { WEEKDAY { @Override void apply() { System.out.println("hi, weekday"); } }, WEEKEND { @Override void apply() { System.out.println("hi, weekend"); } }; abstract void apply(); } }
通过策略枚举的方式,我们把Day的处理逻辑委托给了DayType,个中奥妙,读者可以细细体会。
枚举集合 EnumSet的使用
EnumSet提供了非常方便的方法来创建枚举集合,下面这段代码,感受一下
public class Text { public enum Style { BOLD, ITALIC, UNDERLINE, STRIKETHROUGH } // Any Set could be passed in, but EnumSet is clearly best public void applyStyles(Set<Style> styles) { // Body goes here for(Style style : styles){ System.out.println(style); } } // Sample use public static void main(String[] args) { Text text = new Text(); text.applyStyles(EnumSet.of(Style.BOLD, Style.ITALIC)); } }
这个例子里,我们使用了EnumSet.of方法,轻松创建了枚举集合。
枚举Map EnumMap的使用
假设对于香草(Herb),有一个枚举属性Type(一年生、多年生、两年生)
Herb:
public class Herb { public enum Type { ANNUAL, PERENNIAL, BIENNIAL } private final String name; private final Type type; Herb(String name, Type type) { this.name = name; this.type = type; } @Override public String toString() { return name; } }
现在,假设我们有一个Herb数组,我们需要对这个Herb数组按照Type进行分类存放。
所以接下来,我们需要创建一个Map,value肯定是Herb的集合了,那么用什么作为key呢?
有的人会使用枚举类型的ordinal()方法,这个函数返回int类型,表示枚举遍历在枚举类里的位置,这样做,缺点很明显,由于你的key的类型是int,不能保证传入的int一定能和枚举类里的变量对应上。
所以,在key的选择上,毫无疑问,只能使用枚举类型,也即Herb.Type。
最后还有一个问题,要使用什么Map? Java为枚举类型专门提供了一种Map,叫EnumMap,相比较与其他Map,这种Map在处理枚举类型上更快,有兴趣的同学可以研究一下这个map的内部实现。
下面让我们看看怎么使用EnumMap:
public static void main(String[] args) { Herb[] garden = { new Herb("Basil", Type.ANNUAL), new Herb("Carroway", Type.BIENNIAL), new Herb("Dill", Type.ANNUAL), new Herb("Lavendar", Type.PERENNIAL), new Herb("Parsley", Type.BIENNIAL), new Herb("Rosemary", Type.PERENNIAL) }; // Using an EnumMap to associate data with an enum - Page 162 Map<Herb.Type, Set<Herb>> herbsByType = new EnumMap<Herb.Type, Set<Herb>>( Herb.Type.class); for (Herb.Type t : Herb.Type.values()) herbsByType.put(t, new HashSet<Herb>()); for (Herb h : garden) herbsByType.get(h.type).add(h); System.out.println(herbsByType); }
总结
和int枚举相比,Enum枚举的在类型安全和使用便利上的优势是不言而喻的。
Enum为枚举提供了丰富的功能,如文章中提到的特定于常量的方法实现和策略枚举。
EnumSet和EnumMap是两个为枚举而设计的集合,在实际开发中,用到枚举集合时,请优先考虑这两个。
The above is the detailed content of Detailed explanation of the use of Java enumerations. For more information, please follow other related articles on the PHP Chinese website!