First, the basic knowledge
Enumeration constants are public static members of enumerated types, and their types are enumerated types that declare them. These constants are called self-typed. Because it is a static constant, you can use the relational operator directly to compare the equality of two enumerated constants. Enumeration constant values can also be obtained by the values method and the ValueOf method defined by the enumeration type.
class Solution { enum Color { RED, BLUE, GREEN } publicstatic void main (string[] args) { = color.values (); for (Color c:colors) System.out.println (c); }}
An enumeration constant is an object of its enumerated type, and the constructors and methods can be defined when the enumeration type is defined. All enumerations automatically inherit Java.lang.Enum, some of which are as follows:
- The ordinal method returns the ordinal value of the enumeration constant.
- The CompareTo method returns the difference between the other enumeration constants of the same type.
- The Equals method returns equality with other enumeration constants of the same type.
classSolution {enumColor {RED ("#FF0000"), BLUE ("#0000FF"), GREEN ("#00FF00"); PrivateString Code; Color (String code) { This. Code =Code; } String GetCode () {returnCode; } } Public Static voidMain (string[] args) {System.out.println (color.valueof ("RED"));//Output RedSystem.out.println (color.valueof ("BLUE"));//Output BlueSystem.out.println (color.valueof ("GREEN"));//Output Greencolor[] Colors=color.values (); for(Color c:colors) System.out.println (C.ordinal ()); for(Color i:colors) for(Color j:colors) {System.out.println (I.compareto (j));//back to I.ordinal-j.ordinalSystem.out.println (I.equals (j)); } }}
Java Notes: Enumerations