What is an enumeration?
Enumerations are new features introduced by JDK5. In some cases, the objects of a class are fixed and can be defined as enumerations. In practice, enumeration types can also be used as a specification to guarantee the safety of program parameters. Enumerations have the following characteristics:
- The levels of enumerations and classes and interfaces in Java are the same.
- Enumerations, like classes, have their own properties, methods, and constructors, except that the enumeration is constructed with a private adornment and cannot be constructed from outside. The constructor method is called only when the enumeration value is constructed.
- When you declare an enumeration type using the Enum keyword, you inherit the class from Java by default and
java.lang.Enum
implement the java.lang.Seriablizable
java.lang.Comparable
two interfaces.
- All enumerated values are
public static final
, and non-abstract enumeration classes can no longer derive subclasses.
- Enumerating all instances of a class (enumerated values) must be explicitly listed in the first row of the enumeration class, otherwise this enumeration class will never produce an instance.
- To determine whether an enumeration is the same, use = = equals is the same.
The following are java.lang.Enum
in the class equals()
:
This is final decorated and does not allow subclasses to override public
final Boolean equals (Object other) {return
this==other;
}
Common methods of enumeration
int compareTo(E o)
Compares the order of this enumeration with the specified object. Returns a negative integer, 0, or positive integer, respectively, when the object is less than, equal to, or greater than the specified object. Enumeration constants can only be compared with other enumerated constants of the same enumerated type.
The source code public in the Enum is
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 that contains all the enumeration values that can be used to traverse all enumerated values.
String toString()
Returns the name of this enumeration instance, which is the enumeration value. With the name()
same.
The name () and ToString () public
String ToString () in the Enum () {return
name;
}
Public final String name () {return
name;
}
int ordinal()
Returns the index value (starting from 0) of the enumeration value in the enumeration class, which is the order of the enumeration values in the enumeration declaration, depending on the order in which the enumeration values are declared.
<T extends Enum<T>> valueOf()
Returns an enumerated constant with the specified enumeration type named, which must exactly match the identifier used to declare the enumeration constant in this type (no extra white space characters are allowed). This method corresponds to ToString, so overriding the method toString()
must override the method valueOf()
(we can override the method, but we can't override the method ourselves, and when we rewrite the method, the toString()
valueOf()
toString()
valueOf()
method will automatically rewrite it without our attention.) )
Application of Enumeration
Enumerations are special types that are very similar in usage to ordinary classes.
Instead of a set of constants
public enum Color {
RED, GREEN, BLANK, Yellow
}
Use in switch statements
JDK1.6 switch added support for enumerations
enum Signal {
GREEN, yellow, RED
}
...
switch (color) {case
RED:
color = signal.green;
break;
...
To add a method to the enumeration
The public enum Color {red
("red"), Green ("green"), BLANK ("white"), Yello ("yellow");
Member variable
private String name;
Construction Method
Private Color (String name) {
this.name = name;
}
Get Set method public
String GetName () {return
name;
}
public void SetName (String name) {
this.name = name;
}
}
Implementing interfaces
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 that contains abstract methods
public enum Operation {
//is used to perform addition operations
PLUS {//curly braces are actually an anonymous inner subclass
@Override public
double Calculate (double x, double y) {return
x + y;
}
},
//For performing subtraction operations
minus {//curly bracket is actually an anonymous inner subclass
@Override
Public Double calculate (double x, double y) {
//TODO auto-generated method stub return
xy
}
},
//With To perform multiplication The Times
{//curly braces are actually an anonymous inner subclass @Override public
double calculate (double x, double y) {return
x * y;
}
,
//For performing Division operations
DIVIDE {//curly braces is actually an anonymous inner subclass
@Override public
double Calculate ( Double x, double y) {return
x/y;
}
};
Defines an abstract method for the enumeration class in which all enumerated values in the enumeration class must implement this method public
abstract double calculate (double x, double y);
}
Using enumerations to implement a single example (best practice for a single case)
Benefits:
1. Using the characteristics of the enumeration to achieve a single example
2. Guaranteed thread safety by the JVM
3. Serialization and reflection attacks have been enumerated to resolve
public enum Singleton {
INSTANCE;
Public Singleton getinstance () {
//Add this method is to let others understand how to use, because this implementation is relatively rare. return
INSTANCE
}
}
Other uses of enumerations
Enumset
range(E from, E to)
Gets a range of Set from the enumeration value.
For (Weekdayenum Day:EnumSet.range (Weekdayenum.mon, Weekdayenum.fri)) {
System.out.println (day);
}
of(E first, E... rest)
Creates an enumeration Set that initially contains the specified element.
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 Day");
An enumeration in Android
The enum requires a large amount of memory, and if memory is sensitive, use an enum as little as possible and replace it with a static constant.
However, if you do not use enumerations, there will be some security risks, so the official release of two annotations, can be a compile-time type check, to replace the enumeration. These two annotations are: @IntDef and @StringDef. Located in compile ' com.android.support:support-annotations:+ '.
Using the sample
The use of @StringDef is consistent with @IntDef, for example @IntDef.
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//defined in attribute
private int type;
public void SetType (@QRCodeType. Checker int type) {//defined in parameter
this.type= type;
}
@QRCodeType. Checker//defined in the method (that is, the type that checks the return value) public
int GetType () {returns
type;
}
}
Use recommendations
The most widely used in development is the use of enumerations instead of a set of static constants, which can be overridden using the above annotations.
When an enumeration also contains other features (such as a method that contains other definitions), it cannot be replaced.
Summarize
The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring certain help, if you have questions you can message exchange.