Thinking in Java Enumeration

Source: Internet
Author: User

All enum classes are subclasses of Java.lang.Enum, so custom enumeration classes cannot inherit other classes


Common methods for enumerating classes:

values () :

is a static method that is added to the custom enum class by the compiler

Ordinal ()

ValueOf

Package com.demo.enums;/** * @author Wobendiankun * 2014-10-28 pm 10:09:53 */public class Enumstest {/** * @param args */pub Lic static void Main (string[] args) {valueList (); ordinal (); ValueOf ("A");//avalueof ("F");// Java.lang.IllegalArgumentException:No enum Const class Com.demo.enums.gradetype.f}private static void ValueOf (String Type) {System.out.println (); System.out.println (gradetype.valueof (type));} private static void Ordinal () {System.out.println ();//Gets the ordinal of the enumeration constant for (Gradetype type:GradeType.values ()) { System.out.print (type.ordinal () + "\ T")//01234}}private static void ValueList () {//Gets all the values of the enumeration for (Gradetype type: Gradetype.values ()) {System.out.print (type+ "\ t");//Abcde}}}enum Gradetype {a,b,c,d,e}


Get all enumerated constants by class object

private static void Getvaluesbyclass () {for (Gradetype type:GradeType.class.getEnumConstants ()) {System.out.print ( Type+ "\ t");//abcde}system.out.println ();}


To add a new method to an enumeration class

Note the point:

1. Cannot inherit other than enum, as a normal Java Class 2. You must first define an instance of the enum, and add a semicolon 3 on the last side of the instance sequence          . Construct the access limit to private or default

Package Com.demo.enums;public class Enummethodtest {enum Gradetype {//enum instance A (), B (+), C (+), D (;p) rivate int score; Private Gradetype (int score) {This.score = score;} public int Getscore () {return score;}} /** * @param args */public static void main (string[] args) {Gradetype type=gradetype.valueof ("A"); System.out.println ("Score:" +type.getscore ());//Score: 85}}

A (): Call the constructor of the enumeration


Using interfaces to organize enumerations

Department A has two project groups B, C, department leaders want to be able to unify each project team throws exception code and exception information, do a unified plan, each project group can expand their own anomaly code

Class Diagram:



Depaerrorcode:

Package com.demo.enums.orga;/** Exception Code interface * @author Wobendiankun * 2014-10-28 pm 10:45:23 */public interface Depaerrorcode {/** Get error code * @return */string GetCode ();/** get error message * @return */string getdesc ();}

Projectberrorcode

Package com.demo.enums.orga;/** Project Group B error code interface * @author Wobendiankun * 2014-10-28 pm 10:50:00 */public Interface Projectberrorcode extends Depaerrorcode {}

Projectcerrorcode

Package com.demo.enums.orga;/** project Group C error code interface * @author Wobendiankun * 2014-10-28 pm 10:50:00 */public Interface Projectcerrorcode extends Depaerrorcode {}

Projectbcode

Package com.demo.enums.orga;/** * @author Wobendiankun * 2014-10-28 pm 10:58:47 */public enum Projectbcode implements Proje Ctberrorcode{add_user ("10001", "Add User Failed"), Delete_user ("10002", "Delete user failed");p rivate string Code;private string desc; Private Projectbcode (string code, String desc) {This.code = CODE;THIS.DESC = desc;} @Overridepublic String GetCode () {return this.code;} @Overridepublic String GetDesc () {return this.desc;}}

Depaexception

Package com.demo.enums.orga;/** * @author Wobendiankun * 2014-10-28 pm 10:45:43 */public class Depaexception extends Runtim eexception {public depaexception (Depaerrorcode Depaerrorcode) {super (getmsg (Depaerrorcode));} Static String getmsg (Depaerrorcode depaerrorcode) {return "error code:" +depaerrorcode.getcode () + ", error message:" + Depaerrorcode.getdesc ();}}

Errorcodetest

Package com.demo.enums.orga;/** * @author Wobendiankun * 2014-10-28 pm 10:58:40 */public class Errorcodetest {/** * @param a RGS */public static void Main (string[] args) {add ();//com.demo.enums.orga.depaexception: Error code: 10001, Error message: Add user failed} private static void Add () {new Userserivce (). Add ();}} Class Userserivce{void Add () {throw new depaexception (Projectbcode.add_user);}}


enumeration defines abstract methods

Package com.demo.enums;/** * @author Wobendiankun * 2014-10-28 pm 11:13:19 */public class Enumabstracttest {enum Gradetype { A () {@Overridevoid print () {System.out.println ("excellent");}},b () {@Overridevoid print () {System.out.println ("good");}};/ /define an abstract method, abstract void print ();} public static void Main (string[] args) {gradetype type=gradetype.b;type.print ();//Good}}


Enumset & Enummap




public class Enumsettest {      /**      * @param args      *      /public static void main (string[] args) {           enumset< Type > Set= Enumset.allof (type.class);           print (set);           Set=enumset. noneof (type.class);           print (set);           Set=enumset. of (Type.aa, Type. CC);           print (set);     }      static void  print (Enumset <Type> set) {           System.out. println (set);}     } Enum Type {      aa,bb, CC, Dd,ee, FF     }   


public class Enummaptest {      static enummap <type, invokehandler> map = new Enummap<type, invokehandler> (
    type.class);      static void Init () {           map.put (Type). AA, New Invokehandler () {               @Override public               void handle () {                    System.out. println ("Processed AA ...");}          );           Map.put (Type. CC, new Invokehandler () {               @Override public               void handle () {                    System.out. println ("Processed cc ...");          } );     }      /**      * @param args */public      static void Main (string[] args) {           init ();           Map.get (Type. CC). handle ();           Map.get (Type. AA). Handle ();           Map.get (Type. DD). handle ();     }} Interface Invokehandler {      void handle ();}







Thinking in Java Enumeration

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.