JDK1.5 introduces a new type--enumeration. In Java, although it is a "small" function, but to my development has brought "big" convenience.
Usage One: constant.
Before JDK1.5, we defined constants: public static fianl ..... Now, with enumerations, you can group related constants into an enumeration type, and enumerations provide more methods than constants.
Public enum Color { RED, GREEN, BLANK, YELLOW}
Simple to use
public
class
B {
public
static
void
main(String[] args) {
System.
out
.println( isRed( Color.BLANK ) ) ;
//结果: false
System.
out
.println( isRed( Color.RED ) ) ;
//结果: true
}
static
boolean isRed( Color color ){
if
( Color.RED.
equals
( color )) {
return
true
;
}
return
false
;
}
}
Or the use of switch
Signal color = signal.red;
Public Void Change () {
switch (color) {
Case RED:
color = Signal.green;
Break ;
Case YELLOW:
color = signal.red;
Break
Case GREEN:
color = Signal.yellow;
Break ;
}
}
Usage Two: Methods for overriding enumerations
An example of the ToString () method overlay is given below.
enumcolor{RED ("Red", 1), Green ("green", 2), BLANK ("White", 3), Yello ("Yellow", 4); //member Variables PrivateString name; Private intindex; //Construction Method PrivateColor (String name,intindex) { This. Name =name; This. index =index; } //override Method@Override PublicString toString () {return This. index+ "_" + This. Name; } }
Usage
Color.RED.toString (); Print 1_ Red
Similarly, it can also be a parameter
Enum Execstatus {
WAIT (' 0 '), PROGRESS (' 1 '), SUCCESS (' 2 '), ERROR (' 3 ');
Private char State;
Private Execstatus (char state) {
This.state = State;
}
Public Char GetValue () {
return state;
}
@Override
Public String toString () {
return string.valueof (state);
}
}
Usage
ExecStatus.WAIT.getValue ()//Print 0
Common uses of Java enumeration (enum)