Common uses of Java enumeration (enum)

Source: Internet
Author: User

JDK1.5 introduces a new type--enumeration. In Java, although it is a "small" function, but to my development has brought "big" convenience.

Usage One: constant.

Before JDK1.5, we defined constants: public static fianl ..... Now, with enumerations, you can group related constants into an enumeration type, and enumerations provide more methods than constants.

 Public enum Color {     RED, GREEN, BLANK, YELLOW}

Simple to use
publicclassB {
     public static void main(String[] args) {          System. out .println( isRed( Color.BLANK ) ) ;   //结果: false          System. out .println( isRed( Color.RED ) ) ;     //结果: true      }      static boolean isRed( Color color ){          if ( Color.RED. equals ( color )) {              return true ;          }          return false ;      }   }Or the use of switch

Signal color = signal.red;

  Public Void Change () {

switch (color) {

      Case RED:

color = Signal.green;

Break ;

      Case YELLOW:

color = signal.red;

Break

      Case GREEN:

color = Signal.yellow;

Break ;

}

}

Usage Two: Methods for overriding enumerations

An example of the ToString () method overlay is given below.

enumcolor{RED ("Red", 1), Green ("green", 2), BLANK ("White", 3), Yello ("Yellow", 4); //member Variables    PrivateString name; Private intindex; //Construction Method    PrivateColor (String name,intindex) {           This. Name =name;  This. index =index; }      //override Method@Override PublicString toString () {return  This. index+ "_" + This. Name; }  }
Usage
Color.RED.toString (); Print 1_ Red

Similarly, it can also be a parameter  
Enum Execstatus {

WAIT (' 0 '), PROGRESS (' 1 '), SUCCESS (' 2 '), ERROR (' 3 ');
Private char State;

Private Execstatus (char state) {
This.state = State;
}

Public Char GetValue () {
return state;
}

@Override
Public String toString () {
return string.valueof (state);
}
}

Usage
ExecStatus.WAIT.getValue ()//Print 0

Common uses of Java enumeration (enum)

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.