Directly on the code
Usage one (constant):
Package Com.ou.test;import Com.sun.corba.se.impl.util.sunvmcid;public class Enum {public static void main (string[ ] args) { Weekday day = weekday.five; System.out.println (day);//Direct Output FIVE }}enum weekday{ One,two,three,four,five,six,seven;}
Results:
It looks similar to the static variable used above, and the default ToString method returns the corresponding name.
Usage two (switch):
Package com.ou.test;
public class Enum {
public static void Main (string[] args) {
Color color = Color.green;
switch (color) {
Case RED:
color = Color.green;
Break
Case YELLOW:
color = color.red;
Break
Case GREEN:
color = Color.yellow;
Break
}
SYSTEM.OUT.PRINTLN (color);
}
}
Enum color{
GREEN, YELLOW, RED
}
Results:
usage Three: Add a new method to the enumeration
Package com.ou.test;
public class Enum {
public static void Main (string[] args) {
System.out.println (Color.getname (3));
System.out.println (Color.getindex ("green"));
}
}
Enum color{
Red ("Red", 1), Green ("green", 2), BLANK ("White", 3), Yello ("Yellow", 4);
Member variables
private String name;
private int index;
Construction method
Color (String name, int index) {
This.name=name;
This.index=index;
}
Normal method (find value by index number)
public static String getName (int index) {
For (Color c:color.values ()) {
if (c.getindex () = = index) {
return c.name;
}
}
return null;
}
Normal method (find index number by value)
public static int GetIndex (String name) {
For (Color c:color.values ()) {
if (C.getname () ==name) {
return c.index;
}
}
return-1;
}
Get Set
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;
}
}
Results:
Java enumeration Class (simple to use)