Java enumeration (1)

Source: Internet
Author: User

In actual programming, there are often such "datasets", their values are stable in the program, and the elements in the "dataset" are limited. For example, seven data elements from Monday to Sunday constitute a "dataset" for a week, and four data elements for spring, summer, and autumn constitute a "dataset" for the Four Seasons ". In Java, the easiest way to think of such a dataset is to write it like this. Let's take a Friday workday as an example:

Java code

Public class weekday {

Public static final int Monday = 1;

Public static final int Tuesday = 2;

Public static final int wensday = 3;

Public static final int Thursday = 4;

Public static final int Friday = 5;

}

Now, your class can use constants like weekday. Tuesday. But there are some problems hidden here. These constants are int type constants in Java, which means this method can accept any int type value, even if it does not match any date defined in weekday. Therefore, you need to check the upper and lower bounds. When an invalid value occurs, an illegalargumentexception may be thrown. Moreover, if another date (such as weekday. Saturday) is added later, the upper bound of all codes must be changed to accept the new value. In other words, this scheme may be feasible when using this class with Integer constants, but it is not very effective.

The boss of Joshua Bloch stood up at this moment and put forward a very good pattern in this scenario in his book "objective Java"-type-safe enumeration pattern. In short, this pattern is to give such a constant class A private constructor, and then declare variables of the same type as public static final to the user, for example:

Java code

Public class weekday {

Public static final weekday Monday = new weekday (1 );

Public static final weekday Tuesday = new weekday (2 );

Public static final weekday wensday = new weekday (3 );

Public static final weekday Thursday = new weekday (4 );

Public static final weekday Friday = new weekday (5 );

Public int getvalue (){

Return value;

}

Private int value;

Private weekday (int I ){

This. value = I;

}

// Other methods...

}

The advantage of doing so is that your program now accepts not int type data, but a predefined static final instance (weekday. Tuesday, etc.) of weekday. For example:

Java code

Public void setweekday (weekday ){...}

This avoids program errors caused by passing an invalid int type value (for example,-1) to the method at will. At the same time, it will bring some other benefits: because these enumerated objects are some class instances, so put some required attributes in it to store data; since they are all single-instance, you can use the equals method or the = symbol to compare them.

The enumeration mode proposed by Joshua Bloch is very useful but troublesome. If you have used a language like C/C ++ or Pascal, you will be impressed with their enumeration types. For example, in C/C ++, we can define them as follows:
C/C ++ code

Enum weekday {

Monday,

Tuesday,

Wensday,

Thursday,

Friday

};

Then, you can use the Monday and Tuesday variables in the program. This is convenient, but Java 1.4 and earlier versions do not provide support for enumeration types. Therefore, if you are developing a program using JDK 1.4, you can only write it like Joshua Bloch. This situation has changed since Java 5.0 (codenamed Tiger). JAVA supports the enumeration type at the language level.

Enumeration is a very important new feature of tiger. It is a new type that allows constants to represent specific data fragments, and all of them are expressed in type-safe forms, it is defined using the "Enum" keyword.

Let's first write a simple definition of Enumeration type:

Java code

Public Enum weekday {

Monday, Tuesday, Wensday, Thursday, Friday; // The Last ";" can be written or not.

}

This is very similar to the definition of classes and interfaces! The enumeration type in Tiger is a class defined by the special Syntax "Enum. All enumeration types are subclasses of Java. Lang. enum. This is a new class introduced by tiger. It is not an enumeration type, but it defines the behavior of all enumeration types, as shown in the following table:

Note: although all enumeration types are inherited from Java. Lang. Enum, you cannot bypass the keyword "Enum" and use the method of inheriting Enum directly to define the enumeration type. The compiler will prompt an error to prevent you from doing so.

The five enumerated constants defined in weekday are separated by commas. These constants are "public static final" by default, so you do not have to add "public static final" to them (the compiler will prompt an error ), this is why enumeration constants are named in uppercase letters. In addition, each constant is an instance of the enumeration type weekday. You can. monday is used to obtain the enumerated constants defined in weekday. It can also be similar to weekday oneday = weekday. monday is used to assign values to enumerated variables (you cannot assign values other than enumerated constants and null to enumerated variables, and the compiler will prompt an error ).

How is the enumerated constant initialized as an enumeration type instance? In fact, the answer is very simple. These enumerated constants are initialized through the constructor defined in Enum.
Java code

// Constructor defined in Java. Lang. Enum,

// The two parameters are the names of the defined enumerated constants and their order.

Protected Enum (string name, int ordinal ){

This. Name = Name;

This. ordinal = ordinal;

}

During initialization, the order of enumerated constants is arranged in the declared order. The order of the first enumerated constant is 0.

In addition to the methods provided by Enum, enumeration types also have two hidden static methods related to specific enumeration types: values () and valueof (string arg0 ). The values () method can obtain an array containing all enumeration constants. the valueof method is Java. lang. the simplified version of the valueof method in Enum. You can use it to obtain the enumerated constants matching the current enumeration type based on the passed name.

Let's look at a small example of Enumeration type usage. The requirement requires that information can be output on the specified date. For such a simple requirement, the enumeration type is used here for processing. We have defined an enumeration type that includes five working days. The following code is used for output:

Java code

/**

* The corresponding date information is output based on different dates.

* @ Param weekday indicates the enumerated constants of different dates.

*/

Public void printweekday (weekday ){

Switch (weekday ){

Case Monday:

System. Out. println ("Today is Monday !");

Break;

Case Tuesday:

System. Out. println ("Today is Tuesday !");

Break;

Case wensday:

System. Out. println ("today is wensday !");

Break;

Case Thursday:

System. Out. println ("today is hursday !");

Break;
Case Friday:

System. Out. println ("Today is Friday !");

Break;

Default:
Throw new assertionerror ("unexpected value:" + weekday );

}

}

Before tiger, switch operations can only be performed on Int, short, Char, and byte. In tiger, switch supports the enumeration type, because the enumeration type only contains a limited number of enumeration constants that can be replaced by integers, which is too suitable for the switch statement! As in the code above, if you place an enumeration type variable in the swtich expression, you can directly use the enumerated constant in the enumeration type in the case flag.

Note: There is no Enumeration type prefix in the write method indicated by case, which means you cannot write the code as case operation. Plus. You only need to write it as case plus. Otherwise, the compiler prompts an error message.

As in the above example, although you have exhausted all the enumerated constants of an enumeration type in the case mark, however, we recommend that you add the default identifier at the end (as shown in the code above ). If you add a new enumerated constant to the enumerated type and forget to add the corresponding processing in the switch, it is difficult to find errors.

To better support enumeration types, java. util adds two new classes: enummap and enumset. You can use them to operate enumeration types more efficiently. I will introduce you one by one:

Enummap is a map implementation tailored for enumeration types. Although other map implementations (such as hashmap) can also map enumeration instances to values, using enummap is more efficient: it can only receive instances of the same Enumeration type as key values, in addition, because the number of Enumeration type instances is relatively fixed and limited, enummap uses arrays to store values corresponding to the enumeration type. This makes enummap very efficient.

Tip: enummap uses ordinal () of the enumeration type internally to obtain the declared order of the current instance, and maintains the position of the value corresponding to the enumeration type instance in the array.

The following is a sample code using enummap. The enumerated databasetype contains all currently supported database types. For different databases, some database-related methods need to return different values. In this example, geturl is one.

Java code

// Currently supported Database Type Enumeration type definitions

Public Enum databasetype {

MySQL, Oracle, DB2, sqlserver

}

// Obtain the database URL and the enummap Statement defined in a certain type.

......

Private enummap <databasetype, string> URLs =

New enummap <databasetype, string> (databasetype. Class );

Public databaseinfo (){

URLs. Put (databasetype. DB2, "JDBC: DB2: /// localhost: 5000/sample ");

URLs. Put (databasetype. MySQL, "JDBC: mysql: // localhost/mydb ");

URLs. Put (databasetype. Oracle, "JDBC: oracle: thin: @ localhost: 1521: sample ");

URLs. Put (databasetype. sqlserver, "JDBC: Microsoft: sqlserver: // localhost: 1433; databasename = mydb ");

}

/**

* The corresponding URL is returned based on different database types.

* @ Param type new instance of the databasetype enumeration class

* @ Return

*/

Public String geturl (databasetype type ){

Return this. URLs. Get (type );

}

In actual use, the enummap object URLs is usually filled by the code that is responsible for the initialization of the entire application. For the convenience of demonstration, the class fills in the content by itself.

As in the example, using enummap can easily bind enumeration types to different values in different environments. For example, if geturl is bound to a URL, it may be bound to a database driver in other code.

Enumset is an enumeration type high-performance set implementation. It requires that the enumerated constant to be put in it must belong to the same Enumeration type. Enumset provides many factory methods for initialization, as shown in the following table:

Enumset is implemented as the set interface. It supports traversal of contained enumerated constants:
Java code

For (Operation OP: enumset. Range (operation. Plus, operation. Multiply )){

Dosomething (OP );

}

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.