Java Foundation (III) enumeration usage
Usage One: Constants
public enum Color {
Red,green,red,yellow;
}
Usage Two: custom methods in enumerations
/**
* Custom Methods in enumerations
*/
public enum Color {
Red ("Red", 1), Green ("green", 2), BLANK ("White", 3), YELLOW ("Yellow", 4);
Member variables
public String name;
public int index;
constructor function
Private Color (String name, int index) {
THIS.name = name;
This.index = index;
}
Common methods
public static String getName (int index) {
For (Color c:color.values ()) {
if (c.getindex () = = index) {
return c.name;
}
}
return null;
}
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
public int GetIndex () {
return index;
}
public void Setindex (int index) {
This.index = index;
}
}
Usage Three: Switch
public class TrafficLight {
Color signal = color.red;
public void Change () {
Switch (signal) {
Case RED:
signal = Color.green;
Break
Case GREEN:
signal = Color.yellow;
Break
Case YELLOW:
signal = color.red;
Break
}
}
}
Usage Four: Enumerate implementation interfaces
Enumeration inherits the Java.lang.Enum.java does not support multiple inheritance, but enumerations can implement interfaces.
Usage Five: Enumerate collections
The enumeration collection has Enummap and Enumset two, the key value in the Enummap collection is an enumeration, value can be any type, and numset guarantees that the elements in the collection are not duplicated.
Instance usage:
public static void Testenummap () {
Enummap<light, string> currlight = new Enummap<light, string> (Light.class);
Currlight.put (Light.green, "green light");
Currlight.put (light.red, "red light");
Currlight.put (Light.yellow, "yellow Light");
For (Light aLight:Light.values ()) {
System.out.println ("[key=" + alight.name () + ", value="
+ currlight.get (alight) + "]");
}
}
Re-walk Java--step 3