After Java1.5, the enumeration of new features was introduced, before Java had two ways of defining new types: Classes and interfaces. But in special cases, we can't satisfy our needs, for example, we define a color class, which can only have red,blue,green three values and is not valid for other values. Before we introduce enumerations, we typically use them to privatize their construction methods, and then instantiate three constants inside them, and then take the values. This is not only cumbersome, but also brings more unsafe problems.
Package andy.enumtype.test;/** * @author zhang,tianyou * version:2014-11-24 Morning 11:03:06 * * */public class Color {public static final color red = new Color ("red");p ublic static final color green = new Color ("green");p ublic static fin Al color blue = new Color ("Blue");p rivate color (String name) {this.name = name;} private string Name;public string GetName () {return name;} public void SetName (String name) {this.name = name;} public static color getinstance (int. i) {switch (i) {case 0:return color.red;case 1:return color.green;case 2:return color. Blue;default:return null;}} public static void Main (string[] args) {color color = color.red; System.out.println (Color.getname ());}}
But this only gets the value from red BLUE GREEN three.
The following implementation is implemented in the enumeration:
Package andy.enumtype.test;/** * @author zhang,tianyou * version:2014-11-24 am 11:43:07 * * */public enum Color1 {red ("Black"), Blue ("Blue"), Green ("green");p rivate Color1 (String name) {this.name = name;} private string Name;public string GetName () {return name;} public void SetName (String name) {this.name = name;} public static void Main (string[] args) {Color1 color = color1.red; System.out.println (Color.getname ());//c.ordinal () Gets the ordinal for (Color1 c:color1.values ()) {System.out.println (c.ordinal () + "----" + c.getname ());}}}
It also supports Enumset, Enummap, and other operations.
Java enumeration enum usage and related operations