Java Enum (enumeration) Usage Details + Summary

Source: Internet
Author: User

Enum is called enumeration. It is a new feature introduced in JDK 1.5 and is stored in the Java. lang package.

The following are some of my experiences and conclusions in using Enum, including:

1. Original interface definition constant

2. syntax (Definition)

3. Common Operations such as traversal and switch

4. Introduction to common methods for Enum objects

5. Customize attributes and methods for Enum

6. Application of enumset and enummap

7. Analysis of Enum principles

8. Summary

Original interface definition constant
 
Public interface iconstants {string MON = "mon"; string Tue = "Tue"; string wed = "wed"; string Thu = "Thu"; string Fri = "fri "; string sat = "sat"; string sun = "sun ";}
Syntax (Definition)

To create an enumeration type, use the enum keyword, which implies that all created types are subclasses of the Java. Lang. Enum class (Java. Lang. Enum is an abstract class ). The enumerated type conforms to the general mode.Class Enum <E extends Enum <E>, AndEThe name of the enumerated type. Each value of the enumeration type is mappedProtected Enum (string name, int ordinal)In the constructor, the name of each value is converted into a string, and the ordinal number setting indicates the order in which this setting is created.

 
Package COM. HMW. test;/*** Enumeration Test class * @ author <a href = "mailto: hemingwang0902@126.com"> He mingwang </a> */Public Enum enumtest {Mon, Tue, wed, thu, Fri, SAT, sun ;}

This sectionCodeIn fact, the enum (string name, int ordinal) is called seven times ):

New Enum <enumtest> ("mon", 0); New Enum <enumtest> ("Tue", 1); New Enum <enumtest> ("wed ", 2 );......
Common Operations such as traversal and switch

Sample Code for Traversing Enum and switching:

Public class test {public static void main (string [] ARGs) {for (enumtest E: enumtest. values () {system. out. println (E. tostring ();} system. out. println ("---------------- I am a separation line ----------------"); enumtest test = enumtest. tue; Switch (TEST) {Case Mon: system. out. println ("Today is Monday"); break; Case Tue: system. out. println ("Today is Tuesday"); break ;//...... default: system. out. println (TEST); break ;}}}

Output result:

Montuewedthufrisatsun ---------------- I am a separator ---------------- today is Tuesday
Introduction to common methods for Enum objects

IntCompareto(E o)

Compare this enumeration with the sequence of the specified object.

Class <E>Getdeclaringclass()

Returns the class object corresponding to the enumerated type of this enumerated constant.

StringName()

Return the name of this enumerated constant and declare it in its enumerated declaration.

IntOrdinal()

Returns the ordinal number of an enumerated constant (where it is in the enumeration Declaration, where the ordinal number of an initial constant is zero ).

StringTostring()

 Returns the name of an enumerated constant, which is included in the declaration.

Static<T extends Enum <t> TValueof(Class <t> enumtype, string name)

Returns an enumerated constant of the specified enumeration type with the specified name.

Public class test {public static void main (string [] ARGs) {enumtest test = enumtest. tue; // compareto (e o) Switch (test. compareto (enumtest. mon) {Case-1: system. out. println ("Tue before mon"); break; Case 1: system. out. println ("Tue after mon"); break; default: system. out. println ("the same location of Tue and Mon"); break;} // getdeclaringclass () system. out. println ("getdeclaringclass ():" + test. getdeclaringclass (). getname (); // name () and tostring () system. out. println ("Name ():" + test. name (); system. out. println ("tostring ():" + test. tostring (); // ordinal (). The returned value is system starting from 0. out. println ("ordinal ():" + test. ordinal ());}}

Output result:

Tue after mon getdeclaringclass (): COM. HMW. Test. enumtestname (): tuetostring (): tueordinal (): 1
Customize attributes and methods for Enum

Add the attribute of value and the getvalue () method to the enum object:

 package COM. HMW. test;/*** Enumeration Test class ** @ author  He mingwang  */Public Enum enumtest {Mon (1 ), tue (2), wed (3), Thu (4), FRI (5), sat (6) {@ override public Boolean isrest () {return true ;}}, sun (0) {@ override public Boolean isrest () {return true ;}}; private int value; private enumtest (INT value) {This. value = value;} public int getvalue () {return value;} public Boolean isrest () {return false ;}
Public class test {public static void main (string [] ARGs) {system. out. println ("enumtest. fri value = "+ enumtest. fri. getvalue ());}}

Output result:

 
Value of enumtest. Fri = 5
Application of enumset and enummap
Public class test {public static void main (string [] ARGs) {// use enumset for enumset <enumtest> weekset = enumset. allof (enumtest. class); For (enumtest day: weekset) {system. out. println (day);} // use enummap for enummap <enumtest, string> weekmap = new enummap (enumtest. class); weekmap. put (enumtest. mon, "Monday"); weekmap. put (enumtest. tue, "Tuesday ");//...... for (iterator <entry <enumtest, string> iter = weekmap. entryset (). iterator (); ITER. hasnext ();) {entry <enumtest, string> entry = ITER. next (); system. out. println (entry. getkey (). name () + ":" + entry. getvalue ());}}}
Principle Analysis

although the syntax structure of Enum is different from that of class, a class file is generated after compilation by the compiler. This class file is decompiled to show that a class is actually generated, which inherits java. Lang. Enum . After decompiling ( javap com. HMW. Test. enumtest ), The enumtest obtains the following content:

Public class COM. HMW. test. enumtest extends Java. lang. enum {public static final COM. HMW. test. enumtest mon; public static final COM. HMW. test. enumtest Tue; public static final COM. HMW. test. enumtest wed; public static final COM. HMW. test. enumtest Thu; public static final COM. HMW. test. enumtest Fri; public static final COM. HMW. test. enumtest sat; public static final COM. HMW. test. enumtest sun; static {}; public int getvalue (); Public Boolean isrest (); public static COM. HMW. test. enumtest [] values (); public static COM. HMW. test. enumtest valueof (Java. lang. string); COM. HMW. test. enumtest (Java. lang. string, Int, Int, Com. HMW. test. enumtest );}

Therefore, in fact, Enum is a class, but the Java compiler helps us parse and compile the syntax.

Summary

you can think of Enum as a common class, which can define some attributes and methods. The difference is that Enum cannot use the extends keyword to inherit other classes, because Enum has inherited Java. lang. enum (Java is a single inheritance ).

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.