Three minutes to quickly master Java enum of enum

  • 2020-05-19 04:58:09
  • OfStack

What is an enumeration?

Enumeration is a new feature introduced by JDK5. In some cases, the object of a class is fixed and can be defined as an enumeration. In practice, enumeration type can also be used as a specification to ensure the safety of program parameters. Enumeration has the following characteristics:

Enums in Java are at the same level as classes and interfaces.
Enumeration and class 1 have their own properties, methods and constructors. The difference is that the enumeration constructor can only be modified by private, so it cannot construct objects from the outside. The constructor is called only when an enumeration value is constructed.
When you declare an enumerated type using the enum keyword, you inherit from Java by default java.lang.Enum Class and implemented it java.lang.Seriablizable and java.lang.Comparable Two interfaces.
All enumeration values are public static final , and non-abstract enumeration classes can no longer be subclassed.
All instances of an enumeration class (enumeration values) must be listed explicitly on line 1 of the enumeration class, otherwise the enumeration class will never be able to generate an instance.
To determine if the enumeration is the same, use == and equals as 1.

The following is java.lang.Enum In the class equals() :


//  Here is the final Modified, not allowed for subclass override  
public final boolean equals(Object other) { 
 return this==other;
}

Common methods of enumeration

int compareTo(E o)

Compare this enumeration with the order of the specified objects. Returns a negative integer, zero, or positive integer when the object is less than, equal to, or greater than the specified object. Enumeration constants can only be compared with other enumeration constants of the same enumeration type.


// Enum  The source code 
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 enumeration instance.

static values()

Returns an array containing all enumerated values that can be used to traverse all enumerated values.

String toString()

Returns the name of this enumeration instance, that is, the enumeration value. with java.lang.Seriablizable0 1 sample.


// Enum  In the  name()  and  toString()
public String toString() {
 return name;
}
public final String name() {
 return name;
}

int ordinal()

Returns the index value of the enumeration value in the enumeration class (starting at 0), that is, the order in which the enumeration value is declared, depending on the order in which the enumeration value is declared.

<T extends Enum<T>> valueOf()

Returns an enumeration constant of a specified enumeration type with the specified name, which must exactly match the identifier used to declare enumeration constants in this type (no additional white space characters are allowed). This method corresponds to toString and is therefore overwritten toString() Method 1 must be overwritten valueOf() Method (we can rewrite it toString() Method, but you can't rewrite it yourself valueOf() Method, when we rewrite toString() Method, valueOf() The method is automatically rewritten without our attention.)

Application of enumeration

Enumeration is a special type whose usage is very similar to that of ordinary classes.

Replace 1 set of constants


public enum Color { 
 RED, GREEN, BLANK, YELLOW 
}

Used in the switch statement


// JDK1.6  In the switch Support for enums has been added 
enum Signal { 
 GREEN, YELLOW, RED 
} 

...
switch (color) { 
 case RED: 
  color = Signal.GREEN; 
  break; 
}
...

Add methods to the enumeration


public enum Color { 

 RED(" red "), GREEN(" green "), BLANK(" white "), YELLO(" yellow "); 

 //  Member variables  
 private String name; 
 //  A constructor  
 private Color(String name) { 
  this.name = name; 
 } 

 // get set  methods  
 public String getName() { 
  return name; 
 } 
 public void setName(String name) { 
  this.name = name; 
 } 

}

Implementing an interface


public interface Behaviour { 
 void print(); 
} 

public enum Color implements Behaviour{ 
 RED(" red ", 1), GREEN(" green ", 2), BLANK(" white ", 3), YELLO(" yellow ", 4); 

 // Interface methods  
 @Override 
 public void print() { 
  System.out.println(this.index+":"+this.name); 
 } 
}

An enumeration class that contains abstract methods


public enum Operation {

 //  Used to perform addition operations 
 PLUS { //  The curly braces are actually 1 Anonymous inner subclasses 

  @Override
  public double calculate(double x, double y) {
   return x + y;
  }

 },

 //  Used to perform subtraction 
 MINUS { //  The curly braces are actually 1 Anonymous inner subclasses 

  @Override
  public double calculate(double x, double y) {
   // TODO Auto-generated method stub
   return x - y;
  }

 },

 //  Used to perform multiplication 
 TIMES { //  The curly braces are actually 1 Anonymous inner subclasses 

  @Override
  public double calculate(double x, double y) {
   return x * y;
  }

 },

 //  Used to perform division operations 
 DIVIDE { //  The curly braces are actually 1 Anonymous inner subclasses 

  @Override
  public double calculate(double x, double y) {
   return x / y;
  }

 };

 // Define for the enumeration class 1 All enumeration values in an enumeration class must implement this method 
 public abstract double calculate(double x, double y);

}

Implementing singletons using enums (best practices for singletons)

Benefits:

1. Realize the singleton by using the features of enumeration

2. Thread safety is guaranteed by JVM

3. Serialization and reflection attacks have been resolved by enumeration


public enum Singleton {
 INSTANCE;
 public Singleton getInstance(){
  //  This method was added to let others know how to use it, as this implementation is relatively rare. 
  return INSTANCE;
 }
}

Other USES of enums

EnumSet

range(E from, E to)

Gets Set of a range of 1 segment from the enumeration value.


for(WeekDayEnum day : EnumSet.range(WeekDayEnum.Mon, WeekDayEnum.Fri)) { 
  System.out.println(day); 
}

java.lang.Comparable0

Creates an enumeration Set that initially contains the specified element.

java.lang.Comparable1

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.


// Enum  The source code 
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;
}
0

Enumeration in Android

Enum takes up a large amount of memory. If it is memory sensitive, use Enum as little as possible and replace it with static constants.

However, there are some security concerns if enumerations are not used, so two annotations have been introduced to replace them by doing type checking at compile time. The two annotations are @IntDef and @StringDef. Located in compile 'com. android. support: support - annotations: +'.

Use the sample

The use of @StringDef is related to @IntDef1. Take @IntDef as an example.


// Enum  The source code 
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;
}
1

Use advice

One of the most widely used in development is to replace a set of static constants with an enumeration, which can be done using the above annotation approach.
The enumeration cannot be replaced when it contains other functions, such as methods that contain other definitions.

conclusion

The above is the whole content of this article, I hope the content of this article to your study or work can bring 1 definite help, if you have questions you can leave a message to communicate.


Related articles: