Introduction to Java Enumeration

Source: Internet
Author: User

Enumeration type: A set of enumerations that enumerate constants, which contain some action methods, which are immutable and are typically used as single-instance operations.

The methods that are included

Self-contained static method values () returns an array of enumerated constants in the enumeration class (returned in the order declared by the enumeration constants)

The ToString () method returns the enumeration constant name.

static method valueof (String name) returns the enumeration constant of the specified name (name refers to the value returned by the default ToString method, that is, the type constant)

Ordinal () returns the position of the specified enumeration constant declared in the enumeration type, starting at 0.

Every enumeration constant in an enumeration type is implemented, an abstract method in an enumeration class, and an enumeration constant is a static variable. So the following code enumeration type constants need to be placed before the custom static code block

The cases are as follows:

 PackageCom.effectJava.Chapter3;ImportJava.util.HashMap;ImportJava.util.Map; Public enumOperation {PLUS ("+") {@OverrideintApplyintAintb) {returnA +b; }}, minus ("-") {@OverrideintApplyintAintb) {returnAb; }}, MULTI ("*") {@OverrideintApplyintAintb) {returnAb; }}, divID ("/") {@OverrideintApplyintAintb) {//test code does not need to handle possible exceptions            returnAb;    }    }; //Customizing the ValueOf method    Private Static FinalMap<string, operation>maps; Static{System.out.println ("Initi Static Block"); Maps=NewHashmap<>();  for(Operation Operation:Operation.values ()) {maps.put (operation.symbol, operation); }    }     Public Staticoperation FromString (String symbol) {returnmaps.get (symbol); }    Private FinalString symbol;        Operation (String symbol) {System.out.println (symbol);  This. symbol =symbol; }    Abstract intApplyintAintb); //after the symbol is changed to the unique identifier of the enumeration constant,
It is best to define a fromstring (String symbol) method that returns the enumeration type that uniquely identifies the symbol Public Static voidMain (String ... args) {System.out.println (Operation.PLUS.apply (1, 2));//operation.valueof ("ss");System.out.println (operation.fromstring ("+")); }}

Java Program Initialization Order

1. Parent class static variable 2. Parent class static code block 3. Subclass static variable 4. Subclass static code block 5. Parent class non-static variable 6. Parent class non-static code block, 7. Parent class constructor, 8. Subclass non-static variable 9. Subclass non-static code block 10. Subclass Constructor

Sequence index implements vanilla classification

 PackageCom.effectJava.Chapter3;Importsun.misc.SharedSecrets;ImportJava.util.EnumMap;ImportJava.util.HashSet;ImportJava.util.Set; Public classHerb { Public enumType {Annual, Perennial, Biennial,}Private FinalString name; Private Finaltype type; Herb (String name, type type) { This. Name =name;  This. Type =type; } @Override PublicString toString () {returnname; }//Classification of Plants     Public Static voidMain (String ... args) {Herb herbs[]=Newherb[]{NewHerb ("Herb1", type.perennial),NewHerb ("Herb2", type.annual),NewHerb ("Herb3", type.annual),NewHerb ("Herb4", Type.biennial)}; //1.classify the plant category by enumerating the position ordinal of the constant//constructing an array of categoriesSetNewset[type.values (). length];  for(inti = 0; i < her.length; i++) {Her[i]=NewHashset(); }//Classification of Plants         for(Herb herb:herbs) {her[herb.type.ordinal ()].add (Herb); }         for(inti = 0; i < her.length; i++) {System.out.printf ("%s:%s%n", Herb.Type.values () [i], her[i]); } System.out.println (Sharedsecrets.getjavalangaccess (). getenumconstantsshared (Type.class));


Enummap classification of each herb,//2. Using ENUMMAP to achieve plant classificationSystem.out.println ("Using Enummap to achieve plant classification"); Enummap<type, setNewEnummap<> (Type.class); for(Herb.type t:herb.type.values ()) {typesetenummap.put (T,NewHashset()); } for(Herb h:herbs) {typesetenummap.get (H.type). Add (h); } System.out.println (Typesetenummap); }}

Two implementations of Enummap state transfer

 PackageCom.effectJava.Chapter3;//Transfer Relationship Public enumPhase {SOLID, LIQUID, gas;  Public enumTransition {MELT, FREEZE, boil, condense, SUBLIME, DEPOSIT; Private Static Finaltransition[][] Transitions = {{NULL, MELT, SUBLIME}, {FREEZE,NULL, boil}, {DEPOSIT, condense,NULL}};  Public StaticTransition from (Phase src, Phase dest) {returntransitions[src.ordinal ()][dest.ordinal ()]; }    }}

The code after optimization

 PackageCom.effectJava.Chapter3;ImportJava.util.EnumMap;ImportJava.util.Map;//Transition relationships are expressed through the,map< phase of the map< initiation phase, stage transitions >> Public enumphasemodify {solid,liquid,gas;  Public enumTransition {MELT (solid, LIQUID), FREEZE (LIQUID, solid), boil (LIQUID, gas), condense (gas,        LIQUID), SUBLIME (solid, gas), DEPOSIT (gas, solid); Private Finalphasemodify src; Private Finalphasemodify DST; Transition (phasemodify src, phasemodify DST) { This. src =src;  This. DST =DST; }        Private Static FinalMap<phasemodify, map<phasemodify, transition>> Map =NewEnummap<phasemodify, Map<phasemodify, transition>> (phasemodify.class); Static {             for(phasemodify p:phasemodify.values ()) {Map.put (P,NewEnummap<phasemodify, Transition> (phasemodify.class)); }             for(Transition trans:Transition.values ()) {Map.get (TRANS.SRC). Put (TRANS.DST, trans); }        }         Public StaticTransition from (Phase src, Phase DST) {returnmap.get (SRC). get (DST); }    }}

Introduction to Java Enumeration

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.