What is an enum?
Enumeration is a new feature introduced by JDK5. In some cases, an object of a class is fixed and can be defined as an enum. In actual use, enumeration types can also be used as a specification to ensure the safety of program parameters. Enumeration has the following characteristics:
java.lang.Enum class in Java by default, and implements two interfaces: java.lang.Seriablizable and java.lang.Comparable .public static final , and non-abstract enumeration classes cannot derive subclasses. Here is equals() in java.lang.Enum class:
// This is final modified, and subclasses are not allowed to rewrite public final boolean equals(Object other) { return this==other;} Common methods for enumeration
int compareTo(E o)
Compare the order of this enum with the specified object. When the object is less than, equal to or greater than the specified object, negative integers, zero or positive integers are returned respectively. Enumeration constants can only be compared with other enumeration constants of the same enum type.
// Source code in Enum public final int compareTo(E o) { Enum other = (Enum)o; Enum self = this; if (self.getClass() != other.getClass() && // optimization self.getDeclaringClass() != other.getDeclaringClass()) throw new ClassCastException(); return self.ordinal - other.ordinal;} String name()
Returns the name of this enum instance.
static values()
Returns an array containing all enum values that can be used to iterate through all enum values.
String toString()
Returns the name of this enum instance, that is, the enum value. Same as name() .
// name() and toString() in Enum public String toString() { return name;}public final String name() { return name;} int ordinal()
Returns the index value of the enum value in the enum class (starting from 0), that is, the order of the enum value in the enum declaration, which depends on the order of the enum value declaration.
<T extends Enum<T>> valueOf()
Returns an enumeration constant of the specified enum type with the specified name, the name must exactly match the identifier used to declare the enumeration constant in this type (extra whitespace characters are not allowed). This method corresponds to toString, so if we override toString() method, we must override valueOf() method (we can override toString() method, but we cannot override valueOf() method by ourselves. When we override toString() method, valueOf() method will be automatically rewrite, and we don't need to pay attention to it.)
Application of enumeration
Enumeration is a special type, and its usage is very similar to that of ordinary classes.
Replace a set of constants
public enum Color { RED, GREEN, BLANK, YELLOW } Used in switch statements
// Switch has added support for enum in JDK1.6 enum Signal { GREEN, YELLOW, RED } ...switch (color) { case RED: color = Signal.GREEN; break; }... Add methods to enum
public enum Color { RED("red"), GREEN("green"), BLANK("white"), YELLO("yellow"); // Member variable private String name; // Constructor private Color(String name) { this.name = name; } // get set method public String getName() { return name; } public void setName(String name) { this.name = name; } } Implement the interface
public interface Behaviour { void print(); } public enum Color implements Behaviour{ RED("red", 1), GREEN("green", 2), BLANK("white", 3), YELLO("yellow", 4); //Interface method @Override public void print() { System.out.println(this.index+":"+this.name); } } Enumeration class containing abstract methods
public enum Operation { // Used to perform addition operations PLUS { // The braces part is actually an anonymous internal subclass @Override public double calculation(double x, double y) { return x + y; } }, // Used to perform subtraction operations MINUS { // The braces part is actually an anonymous internal subclass @Override public double calculation(double x, double y) { // TODO Auto-generated method stub return x - y; } }, // Used to perform multiplication operations TIMES { // The braces part is actually an anonymous internal subclass @Override public double calculation(double x, double y) { return x * y; } }, // Used to perform division operation DIVIDE { // The curly braces part is actually an anonymous internal subclass @Override public double calculate(double x, double y) { return x / y; } }; //Define an abstract method for this enumeration class. All enum values in the enumeration class must implement this method public abstract double calculate(double x, double y);} Implementing singletons with enumerations (best practice for singletons)
benefit:
1.Use the features of enumeration to implement single cases
2. The JVM ensures thread safety
3. Serialization and reflection attacks have been resolved by enumeration
public enum Singleton { INSTANCE; public Singleton getInstance(){ // Add this method to let others understand how to use it, because this implementation method is relatively rare. return INSTANCE; }} Other usage of enumeration
EnumSet
range(E from, E to)
Get a range of Set from the enum value.
for(WeekDayEnum day : EnumSet.range(WeekDayEnum.Mon, WeekDayEnum.Fri)) { System.out.println(day); } of(E first, E... rest)
Creates an enumeration set that originally contains the specified elements.
noneOf(Class<E> elementType)
Creates an empty enumeration Set with the specified element type.
EnumMap
EnumMap(Class<K> keyType)
Creates an empty enumeration map with the specified key type.
Map<Weather, String> enumMap = new EnumMap<Weather, String>(Weather.class);enumMap.put(Weather.Sunny, "sunny");enumMap.put(Weather.Rainy, "rainy");
Enumeration in Android
Enum needs to occupy a large amount of memory. If it is sensitive to memory, please try to use Enum as little as possible and replace it with a static constant.
However, if you do not use enumeration, some security risks will arise, so the official has launched two annotations, which can be type checked during the compilation period to replace enumeration. These two annotations are: @IntDef and @StringDef. Located in compile 'com.android.support:support-annotations:+' .
Example of usage
The use of @StringDef is consistent with @IntDef. Here we take @IntDef as an example.
public interface QRCodeType { int WECHAT = 0; int ALIPAY = 1; @IntDef({WECHAT , ALIPAY }) @Retention(RetentionPolicy.SOURCE) @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER}) @interface Checker { }}public class QRCode { @QRCodeType.Checker // Define in the attribute private int type; public void setType(@QRCodeType.Checker int type) { // Define in the parameter this.type= type; } @QRCodeType.Checker // Define in the method (that is, check the type of return value) public int getType() { return type; }} Recommendations for use
The most widely used range in development is to use enumerations instead of a set of static constants. In this case, the above annotation method can be used instead.
When an enumeration also contains other functions (such as: including other defined methods), it cannot be replaced.
Summarize
The above is the entire content of this article. I hope the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate.