Summary of Java Enumeration type usage

Source: Internet
Author: User

Note: Read the section effective Java for the enum, take notes, and most of the code below is from the effective Java book

An enumeration type is a legitimate worthwhile type that consists of a fixed set of constants.

The benefit of using enumerations: A, because there is no constructor to access, the enumeration type is true final;

B, enumeration types provide type safety at the time of class compilation. For example, when declaring an apple with a parameter type of enum type in a function, any non-null object passed to the parameter when the method is called must be one of the values of apple, but it cannot be guaranteed with a static constant;

C, multiple enumeration types with constants of the same name can coexist peacefully, each with its own namespace

D, enumeration types allow the addition of arbitrary methods and domains, and can implement interfaces.

1, a common set of simple enumerations

Such as:

 Public enum Apple {    Fuji,pippin,cranny_smith}

2, enumeration with a specific value (customizable method)

 Public enumApple {FUJI (1), Pippin (2), Cranny_smith (3); Private Final intCode; Apple (intcode) {         This. Code =Code; }     Public intGetCode () {returnCode; }     Public StaticApple Fromcode (intcode) {         for(Apple apple:Apple.values ()) {if(Apple.getcode () = =code)returnApple; }        return NULL; }}

3, multiple parameters, with arithmetic methods

 Public enumPlanet {MERCURY (3.303e+23, 2.4397e6), VENUS (4.869e+24, 6.0518e6), EARTH (5.976e+24, 6.37814e6), MARS (6.421e+23, 3.3972e6), JUPITER (1.9e+27, 7.1492e7), SATURN (5.688e+26, 6.0268e7), URANUS (8.686E+25, 2.5559e7), NEPTUNE (1.024e+26, 2.4746e7), PLUTO (1.27e+22, 1.137e6); Private Final DoubleMass; Private Final Doubleradius; Private Final Doublesurfacegravity;//m/s^2     Public Static Final DoubleG = 6.67300E-11; Planet (DoubleMassDoubleradius) {         This. Mass =Mass;  This. Radius =radius; Surfacegravity= G * Mass/(RADIUS *radius); }     Public Doublemass () {returnMass; }     Public Doubleradius () {returnradius; }     Public DoubleSurfaceweight (DoubleOthermass) {        returnOthermass *surfacegravity; }}

4, there are different methods depending on the constants.

The switch method----not recommended (it is possible that a new constant was added but not added to the switch)

 Public enumOperation {PLUS ("+"), minus ("-"), Times ("*"), DIVIDE ("/"); Private FinalString symbol; Operation (String symbol) { This. symbol=symbol; }         PublicString Getsymbol () {returnsymbol; }    DoubleApplyDoubleXDoubley) {        Switch( This){         CasePLUS:returnX +y;  CaseMinus:returnX-y;  CaseTimes:returnX *y;  CaseDIVIDE:returnX/y; }        Throw NewAssertionerror ("Unknown operation:" + This); }

Recommended: Constant-specific Method implementation

 Public enumOperation {PLUS ("+") {         Public DoubleApplyDoubleXDoubley) {returnX +y; }}, minus ("-") {         Public DoubleApplyDoubleXDoubley) {returnX-y; }}, Times ("*") {         Public DoubleApplyDoubleXDoubley) {returnX *y; }}, DIVIDE ("/") {         Public DoubleApplyDoubleXDoubley) {returnX/y;    }    }; Private FinalString symbol; Operation (String symbol) { This. symbol =symbol; }     PublicString Getsymbol () {returnsymbol; }     Public Abstract DoubleApplyDoubleXDoubley);}

5, Policy enumeration strategy enum

Let's take a look at the situation: work hours for a week, 8 hours of work, extra overtime, weekends work overtime.

First we can use switch to do it, so it looks very simple.

 Public enumPayrollday {MONDAY, Tuesday, Wednesday, Thursday, Firday, SATURDAY, SUNDAY; Private Static Final intHours_per_shift = 8; DoublePayDoubleHoursworked,Doublepayrate) {        DoubleBasepay = hoursworked *payrate; DoubleOvertimepay; Switch( This) {         CaseSATURDAY: CaseSunday:overtimepay= hoursworked * PayRate * 2; default: Overtimepay= hoursworked <= hours_per_shift? 0: (hoursworked-hours_per_shift) * PayRate * 2;  Break; }        returnBasepay +Overtimepay; }}

But it is also possible that the above mentioned is not rigorous, when the enumeration constant increases, the switch may forget to join

The policy enumeration is used as follows:

 Public enumpayrollday {MONDAY (Paytype.weekday), Tuesday (Paytype.weekday), Wednesday (Paytype.weekday), Thursday (P    Aytype.weekday), Firday (Paytype.weekday), SATURDAY (Paytype.weekend), SUNDAY (paytype.weekend); Private FinalPayType PayType; Payrollday (PayType paytype) { This. PayType =PayType; }     PublicPayType Getpaytype () {returnPayType; }    DoublePayDoubleHoursworked,Doublepayrate) {        returnPaytype.pay (hoursworked, payrate); }    enumPayType {WEEKDAY {@OverrideDoubleOvertimepay (DoubleHoursDoublepayrate) {                returnHours < Hours_per_shift? 0: (Hours-hours_per_shift)* PayRate * 2; }}, WEEKEND {@OverrideDoubleOvertimepay (DoubleHoursDoublepayrate) {                returnHours * PayRate * 2;        }        }; Private Static Final intHours_per_shift = 8; Abstract DoubleOvertimepay (DoubleHoursDoublepayrate); DoublePayDoubleHoursworked,Doublepayrate) {            DoubleBasepay = hoursworked *payrate; returnBasepay +Overtimepay (hoursworked, payrate); }    }}

6, the above examples do not recommend time switch, then when to use it

The switch statement in the enumeration applies to adding constant-specific behavior to an external enumeration type. Example: operation if you want him to have a way to return the corresponding inverse

 Public StaticOperation Inverse (Operation op) {Switch(OP) { CasePLUS:returnOperation.minus;  Caseminus:returnOperation.plus;  CaseTimes :returnOperation.divide;  CaseDIVIDE:returnOperation.times; default:            Throw NewAssertionerror ("Unknown operation:" +op); }    }

Summary of Java Enumeration type usage

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.