JDK1.5 introduces a new type-enumeration, and the advent of enumerations brings great convenience in everyday development.
Common Methods One: constants
JDK1.5 before we usually define system constants, basic is the public static final ... After the enumeration, we can say that enumerations are encapsulated in enumerations.
Public enum Color { Yellor,red,balck}
Common method Two: Switch
Public classTest { Public Static voidMain (string[] args) {Light color=Light.green; SYSTEM.OUT.PRINTLN (change (color)); }/*** Enumerate Switch * *@paramColor *@return */ Private Staticstring Change (light color) {string Remind=NULL; Switch(color) { CaseRed:color=Light.green; Remind= "Red Stop"; Break; CaseGreen:color=Light.green; Remind= "Green Line"; Break; CaseYellor:color=Light.yellor; Remind= "Yellow light is on, wait."; Break; default: Break; } returnremind; }}
Common methods Three: enumeration traversal
enumLight {yellor, RED, GREEN} Public classTest { Public Static voidMain (string[] args) {enumiterator (); } /*** Enumeration Traversal*/ Private Static voidEnumiterator () { for(Light light:Light.values ()) {if(Light.equals (Light.green)) {System.out.println ("Green Line"); } Else if(Light.equals (light.red)) {System.out.println ("Red Stop."); } Else if(Light.equals (Light.yellor)) {System.out.println ("Yellow light is on, wait."); } } }}
Common Method Four: Adding a new method to an enumeration class
Public enumCountryicon {China ("China", "China.icon"), USA ("USA", "Usa.icon")),; PrivateString Country; PrivateString icon; PrivateCountryicon (String country, string icon) { This. Country =Country; This. Icon =icon; } PublicString getcountry () {returnCountry; } Public voidSetcountry (String country) { This. Country =Country; }//Get the corresponding icon by entering a country name Public Staticstring GetIcon (String country) { for(Countryicon countryIcon:CountryICON.values ()) {if(Countryicon.getcountry (). Equals (country)) {returnCountryicon.icon; } } return NULL; } Public voidSetIcon (String icon) { This. Icon =icon; }}
Common ways to use Java enumerations