Java (Enum) enumeration usage detailed _java

Source: Internet
Author: User
Tags comparable readable

Concept

enum, called enumeration, is the new feature introduced in JDK 1.5.

In Java, enum types that are decorated by keywords are enumerated types. The form is as follows:

Enum Color {RED, GREEN, BLUE}

If the enumeration does not add any methods, the enumeration value defaults to the ordered value starting at 0. An example of a Color enumeration type, whose enumerated constants are sequentially red:0,green:1,blue:2

Benefits of enumerations: You can organize constants and manage them uniformly.

Typical application scenarios for enumerations: Error codes, state machines, and so on.

The nature of the enumeration type

Although enum it looks like a new type of data, in fact, an enum is a restricted class and has its own method.

When you create an enum, the compiler generates a related class for you, which inherits from the java.lang.Enum .

java.lang.Enumclass declaration

Public abstract class Enum<e extends Enum<e>>
    implements Comparable<e>, Serializable {...}

Methods of Enumeration

In an enum, some basic methods are provided:

values(): Returns an array of enum instances, and the elements in that array are strictly persisted in the order in which they are declared in the enum.

name(): Returns the instance name.

ordinal(): Returns the order of the instance Declaration, starting at 0.

getDeclaringClass(): Returns the type of enum to which the instance belongs.

equals(): Determines whether it is the same object.

You can use = = to compare enum instance.

In addition, the java.lang.Enum interface is implemented Comparable and the Serializable CompareTo () method is also provided.

Example: The basic method of demonstrating an enum

public class Enummethoddemo {enum Color {RED, GREEN, BLUE;}
  Enum Size {big, middle, SMALL}
    public static void Main (String args[]) {System.out.println ("=========== Print all Color ===========");
    For (Color c:color.values ()) {System.out.println (c + "ordinal:" + c.ordinal ());
    } System.out.println ("=========== Print all Size ===========");
    For (Size s:size.values ()) {System.out.println (S + "ordinal:" + s.ordinal ());
    Color green = Color.green;
    System.out.println ("Green name ():" + green.name ());
    System.out.println ("Green Getdeclaringclass ():" + Green.getdeclaringclass ());
    System.out.println ("Green hashcode ():" + Green.hashcode ());
    System.out.println ("Green compareTo color.green:" + green.compareto (color.green));
    System.out.println ("Green equals Color.green:" + green.equals (color.green));
    System.out.println ("Green equals Size.middle:" + green.equals (size.middle)); System.out.println ("Green equals1: "+ green.equals (1)");
  System.out.format ("green = Color.Blue:%b\n", green = = Color.Blue);

 }
}

Output

=========== Print all Color ===========
RED ordinal:0
GREEN ordinal:1
BLUE ordinal:2
=========== Print All Size =========== big
ordinal:0
Middle ordinal:1
SMALL ordinal:2
Green name (): Green
Green getd Eclaringclass (): Class Org.zp.javase.enumeration.enumdemo$color
Green Hashcode (): 460141958
Green CompareTo color.green:0
green equals Color.GREEN:true
green equals Size.MIDDLE:false
green equals 1:FA LSE
GREEN = = Color.BLUE:false

Attributes of an enumeration

The attributes of an enumeration are summed up in a sentence:

In addition to being unable to inherit, it can basically be enum seen as a regular class.

But this sentence needs to be divided to understand, let us carefully.

Enumeration to add a method

As mentioned in the concept section, the enumeration value defaults to the ordered value starting from 0. So here's the question: How to display the assignment for the enumeration.

Java is not allowed = to assign values to enumerated constants

If you have contact with C + +, you will naturally think of the assignment symbol = . An enum in a C + + language that can be assigned a value with an assignment symbol = displayed as an enumerated constant, but unfortunately, the use of an assignment symbol = To assign a value to an enumerated constant is not allowed in the Java syntax.

Example: An enumeration declaration in C + + language

typedef enum{One
  = 1,
  two,
  THREE = 3,
  TEN = number
;

Enum can add common method, static method, abstract method, construct method

Although Java cannot directly assign a value to an instance, it has a better solution: adding methods for an enum to indirectly implement display assignments.

When you create enum , you can add more methods to it, or even add a construction method to it.

Note One detail: If you want to define a method for an enum, you must add a semicolon at the end of the last instance of the enum. In addition, in an enum, you must first define an instance and you cannot define a field or method in front of the instance. Otherwise, the compiler will complain.

Example: A comprehensive show of how to define common methods, static methods, abstract methods, and construction methods in enumerations

public enum ErrorCode {
  OK (0) {public
    String getdescription () {return
      "successful";
    }
  },
  error_a (100 {Public
    string getdescription () {return
      ' Error a ';
    }
  },
  error_b {public
    string GetDescription () {return
      "error B";
    }
  };

  private int code;
  
  Construct method: The constructor method of an enum can only be declared as private or without permission
  private errorcode (int number) {//constructor
    this.code = number;
  }
  public int GetCode () {//normal method return
    code;
  }//Common method public
  abstract String getdescription ();//abstract method 
   
    public static void Main (String args[]) {//static method for
    (ErrorCode s:errorcode.values ()) {
      System.out.println ("C Ode: "+ s.getcode () +", Description: "+ s.getdescription ());}}}



   

Note: The above example is not desirable, just to show enumeration support to define various methods. The following is a simplified example

Example: Definition of an error code enumeration type

This example is identical to the execution result of the previous example.

public enum Errorcodeen {
  ok (0, "success"),
  error_a (100, "Error A"),
  Error_b (200, "Error B");

  Errorcodeen (int number, String description) {
    This.code = number;
    this.description = description;
  }
  private int code;
  Private String description;
  public int GetCode () {return
    code;
  }
  Public String GetDescription () {return
    description;
  }
  public static void Main (String args[]) {//static method for
    (Errorcodeen s:errorcodeen.values ()) {
      System.out.println ("Code:" + s.getcode () + ", Description:" + s.getdescription ());}}}

Enumerations can implement interfaces

enum Interfaces can be implemented like generic classes.

The same is true of the error code enumeration class in the previous section, which can constrain its methods by implementing an interface.

Public interface Inumberenum {
  int getcode ();
  String getdescription ();
}

Public enum ERRORCODEEN2 implements Inumberenum {
  ok (0, "success"),
  error_a (100, "Error A"),
  Error_b (200, "Error B");

  ERRORCODEEN2 (int number, String description) {
    This.code = number;
    this.description = description;
  }
  
  private int code;
  Private String description;

  @Override public
  int GetCode () {return
    code;
  }

  @Override public
  String getdescription () {return
    description
  }
}

Enumeration can not inherit

An enum cannot inherit another class, and of course, another enum cannot be inherited.

Because you enum actually inherit from java.lang.Enum a class, and Java does not support multiple inheritance, an enum cannot inherit another class, and of course it cannot inherit another enum .

Application Scenarios for enumerations

Organization constants

Before JDK1.5, defining constants in Java is a public static final TYPE a form of this. With enumerations, you can organize the constants associated with relationships to make your code more readable and secure, and you can use enumerations to provide the method.

The format of an enumeration declaration

Note: If you do not define a method in the enumeration, you can also add commas, semicolons, or nothing after the last instance.

The following three ways of declaring are equivalent:

Enum Color {red, green, blue}
enum color {red, green, Blue,}
enum color {red, green, blue;}

Switch state machine

We often use switch statements to write state machines. After JDK7, the switch has supported int、char、String、enum the parameters of the type. With these types of arguments, the switch code that uses enumerations is more readable.

Enum Signal {RED, yellow, GREEN} public

static String gettrafficinstruct (Signal Signal) {
  String instruct = "Semaphore failure ";
  Switch (signal) {case
    red:
      instruct = "Red Stop";
      break;
    Case YELLOW:
      instruct = "Yellow light Please note";
      break;
    Case GREEN:
      instruct = "Green Line";
      break;
    Default: Break
      ;
  }
  return instruct;
}

Organization enumeration

An enumeration of similar types can be organized through interfaces or classes.

However, it is generally organized by means of interfaces.

The reason is that the Java interface is automatically added to the enum type at compile timepublic staticModifiers; Java classes are automatically compiled toenum Type PlusstaticModifier. Do you see the difference? Yes, that is to say, organize in a class enum, if you don't modify it to public, you can only access it in this package.

Example: Organizing an enum in an interface

Public interface Plant {
  enum vegetable implements Inumberenum {
    POTATO (0, "potato"),
    tomato (0, "tomatoes");

    Vegetable (int number, String description) {
      This.code = number;
      this.description = description;
    }

    private int code;
    Private String description;

    @Override public
    int GetCode () {return
      0;
    }

    @Override public
    String getdescription () {return
      null;
    }
  }

  Enum Fruit implements Inumberenum {Apple
    (0, "Apple"),
    Orange (0, "orange"),
    BANANA (0, "banana");

    Fruit (int number, String description) {
      This.code = number;
      this.description = description;
    }

    private int code;
    Private String description;

    @Override public
    int GetCode () {return
      0;
    }

    @Override public
    String getdescription () {return
      null;
    }
}}

Example: Organizing an enum in a class

This example works the same as the previous example.

public class Plant2 {public
  enum vegetable implements Inumberenum {...}//ellipsis code public
  enum Fruit implements Inum Berenum {...}//ellipsis code
}

Policy enumeration

A policy enumeration is shown in Effectivejava. This enumeration sorts the enumeration constants by enumerating the nested enumerations.

This approach, while not simple to switch statements, is more secure and flexible.

Example: Example of a policy enumeration in Effectviejava

Enum Payrollday {MONDAY (Paytype.weekday), Tuesday (Paytype.weekday), Wednesday (Paytype.weekday), Thursday (PAYTYP

  E.weekday), FRIDAY (Paytype.weekday), SATURDAY (Paytype.weekend), SUNDAY (paytype.weekend);

  Private final PayType PayType;
  Payrollday (PayType paytype) {this.paytype = PayType;
  Double Pay (double hoursworked, double payrate) {return Paytype.pay (hoursworked, payrate); }//Policy enumeration private Enum PayType {weekday {double overtimepay (double hours, double payrate) {retur N Hours <= hours_per_shift?
      0: (hours-hours_per_shift) * PAYRATE/2;
      }, weekend {Double overtimepay (double hours, double payrate) {return hours * PAYRATE/2;
    }
    };

    private static final int hours_per_shift = 8;

    Abstract double Overtimepay (double hrs, double payrate);
      Double Pay (double hoursworked, double payrate) {Double Basepay = hoursworked * payrate; return Basepay +Overtimepay (hoursworked, payrate);

 }
  }
}

Test

SYSTEM.OUT.PRINTLN ("Hourly rate 100 of people working 8 hours of income in Friday:" + PayrollDay.FRIDAY.pay (8.0));
SYSTEM.OUT.PRINTLN ("Hourly rate 100 of people working 8 hours of income in Saturday:" + PayrollDay.SATURDAY.pay (8.0, 100));

Enumset and Enummap

Java provides two tool classes--enumset and enummap that facilitate the operation of the enum.

EnumSet is a high-performance implementation of the enumeration type Set . It requires that the enumerated constants put into it must belong to the same enumeration type.

enummap is a map implementation specifically tailored for enumerated types. Although using the other map implementations (such as HashMap) can also complete enumeration type instances to worthwhile mappings, But using Enummap is more efficient: it can only receive instances of the same enumerated type as key values, and because the number of enumerated type instances is relatively fixed and limited, ENUMMAP uses arrays to hold values corresponding to enumerated types. This makes the enummap very efficient.

Enumset use of
System.out.println ("enumset display");
enumset<errorcodeen> Errset = Enumset.allof (errorcodeen.class);
for (Errorcodeen e:errset) {
  System.out.println (e.name () + ":" + e.ordinal ());
}

Enummap use of
System.out.println ("enummap display");
Enummap<statemachine.signal, string> errmap = new Enummap (StateMachine.Signal.class);
Errmap.put (StateMachine.Signal.RED, "red Light");
Errmap.put (StateMachine.Signal.YELLOW, "yellow Light");
Errmap.put (StateMachine.Signal.GREEN, "green light");
For (iterator<map.entry<statemachine.signal, string>> iter = Errmap.entryset (). iterator (); Iter.hasNext ( );) {
  map.entry<statemachine.signal, string> Entry = Iter.next ();
  System.out.println (Entry.getkey (). Name () + ":" + entry.getvalue ());
}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.