[Java5 new feature] Enumeration

Source: Internet
Author: User

What is an enumeration type

If you define a class to complete enterprise employee information, employee information includes information such as name, age, and position (three roles for the worker, manager, and Boss), complete with the following code:

 Public classDemo {PrivateString name;PrivateInteger age;PrivateString role; PublicStringGetrole() {returnRole } Public void Setrole(String role) { This. role = role; } Public Static void Main(string[] args) {Demo EMP1 =NewDemo (); Emp1.setrole ("WORKER"); Demo EMP2 =NewDemo (); Emp2.setrole ("MANAGER"); Demo Emp3 =NewDemo (); Emp3.setrole ("Boss"); list<demo1> list =NewArraylist<demo1> ();        List.add (EMP1);        List.add (EMP2); List.add (Emp3); for(inti =0; I < list.size (); i++) {System. out. println (list.Get(i). Getrole ()); }    }}

In the code above, we can see that when you set up a position role for an employee, you can set other roles that are not in demand. This makes our code security very low (unexpected values), and the code is not very readable. We can rewrite the above code as follows:

 Public classDemo {PrivateString role; Public Static void Main(string[] args) {Demo EMP1 =NewDemo ();        Emp1.role = Role.worker; Demo EMP2 =NewDemo ();        Emp2.role = Role.manager; Demo Emp3 =NewDemo (); Emp3.role ="Boss"; list<demo2> list =NewArraylist<demo2> ();        List.add (EMP1);        List.add (EMP2); List.add (Emp3); for(inti =0; I < list.size (); i++) {System. out. println (list.Get(i). role); }}}class Role { Public StaticFinal String BOSS ="BOSS"; Public StaticFinal String MANAGER ="MANAGER"; Public StaticFinal String WORKER ="WORKER";}

With this rewrite, the readability of the code has improved. However, there can still be unexpected other values in the role of the job, so the result is something we don't want to see. So, we need to continue rewriting the above code:

 Public classDemo {PrivateRole role; Public Static void Main(string[] args) {Demo EMP1 =NewDemo ();        Emp1.role = Role.boss; Demo EMP2 =NewDemo ();        Emp2.role = Role.manager; Demo Emp3 =NewDemo (); Emp3.role ="Boss";//This will be an error at this timelist<demo3> list =NewArraylist<demo3> ();        List.add (EMP1);        List.add (EMP2); List.add (Emp3); for(inti =0; I < list.size (); i++) {System. out. println (list.Get(i). role); }}}class Role { Public StaticFinal Role BOSS =NewRole (); Public StaticFinal Role MANAGER =NewRole (); Public StaticFinal Role WORKER =NewRole ();Private Role() { }}

When the above code is overwritten, the code security and readability issues are resolved. However, the Java 5 release provides an easier way to solve this problem:

publicclass Demo {    private Role role;    publicstaticvoidmain(String[] args) {        new Demo();        emp.role = Role.BOSS;    }}enum Role {    WORKER, MANAGER, BOSS;}

The "enum" keyword here represents the enumeration type, meaning that there are three positions for worker, manager and boss in the position and can only be selected in these three types. The worker, manager, and boss three members in the enumeration type are actually a role object.

Enumerations and switch

From the above discussion, we can see that enumerations are well suited for use in switch statements, so let's look at a case code:

 Public classDemo {PrivateRole role; Public Static void Main(string[] args) {Demo emp =NewDemo (); Emp.role = Role.boss;Switch(Emp.role) { CaseWorker:system. out. println ("This is the employee role."); Break; CaseManager:system. out. println ("This is the manager role."); Break; CaseBoss:system. out. println ("It's the boss's role."); Break; }}enumRole {WORKER, MANAGER, BOSS;}

note that in a switch statement, you cannot use the enumeration class name, such as "Case Role.worker". Because the compiler will judge each enumeration type according to the Emp.role in the switch statement.

Constructors for enum types

You can also customize the constructor by having the default constructor in the enumeration class. However, there are some issues to be aware of when customizing the constructor.

The code for using the default constructor is as follows:

publicenum Role {    WORKER, MANAGER, BOSS;    privateRole() { }}

It is important to note that:

    • If you want to define a constructor, add the delimiter ";" In the last enumeration item.
    • Constructors can only use the private modifier.

The code for using the custom constructor is as follows:

publicenum Role {    WORKER("WORKER"), MANAGER("MANAGER"), BOSS("BOSS");    privateRole(String role) {        System.out.println(role);    }}

If the custom constructor receives parameters, the corresponding information needs to be passed in the enumeration. This is done by adding "()" after enumerating the items and passing them directly.

Member of enum type

In an enumeration class, you can include not only constructors, but also member variables and member methods. For example, the following code:

publicenum Role {    WORKER, MANAGER, BOSS;    private String role;    publicgetRole() {        return role;    }    publicvoidsetRole(String role) {        this.role = role;    }}

However, it is important to note that both the constructor and the member, the enumeration class must first be defined as an enumerated item, and the other content has to be behind the enumeration.

An enumeration class can also contain abstract methods:

 Public enumRole {WORKER {@Override Public void Show() {System. out. println ("WORKER"); }}, MANAGER {@Override Public void Show() {System. out. println ("MANAGER"); }}, BOSS {@Override Public void Show() {System. out. println ("MANAGER"); }    }; Public Abstract void Show();}

Of course, if an enumeration class contains an abstract method, the enumeration must implement the abstract method.

Enumeration type common APIs

In fact, the enumeration classes we use are subclasses of the Java.lang.Enum class and inherit all the methods of the enum class. Common methods are as follows:

    • Name (): Gets the name of the enumeration item.
    • Ordinal (): Gets the index value of the enumerated item, starting with the index value from "0".
    • ValueOf (class Enumclass, String name): Gets the corresponding enumeration class object.

The common methods for customizing enum classes are as follows:

    • valueof (String name): Gets the corresponding enumeration class object.
    • VALUES (): Although this method is not found in the JDK document, each enumeration class has the method, which is convenient for traversing all enumerated values of the enumeration class.

Reprint NOTE: Please indicate the author and the original link, thank you!

[Java5 new feature] 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.