Java Enumeration type detailed

Source: Internet
Author: User
Tags case statement modifier

1. Enumeration types

1.1 Introduction to enumeration types

J2SE 5.0 and the previous JDK have two basic ways to define new types: through classes and interface. These two approaches seem to be sufficient for most object-oriented programming. But in some special cases, these methods are not appropriate. For example, we want to define a type Priority, which can only accept high, Medium, and low three values. Any other value is illegal. J2SE 5.0 before JDK can be constructed this type, but need to do a lot of work, may bring to be like unsafe (type security problem???) and other potential problems, and the enumeration type (enum) of J2SE 5.0 avoids these problems.

Eclipse is the most common development platform for Java programmers, and Eclipse 3.1 provides support for J2SE 5.0, which is J2SE The new features of 5.0 provide help tools. On support for enumerated types, it provides not only the creation template for enumerated types, but also error hints and help modifications for various development errors of enumerated types.

This article first describes the basic concepts of creating enumerated types and how to create enumerated types on the Eclipse 3.1 platform, and then we illustrate the application of enumeration types by example in the Eclipse 3.1 development environment.

1.2 Creating an enumeration type

The following example shows how to create a most basic enumeration type: Listing 1. Enumeration type definition


Public enum Priority {high, Medium, low};

It includes a keyword enum, a new enumeration type name Priority, and a set of values defined for Priority.

On the Eclipse 3.1 platform, follow these steps to build the enumeration type: (Eclipse 3.1 Provides a new enumeration Type Creation Wizard (Wizard) to facilitate user creation of enumeration types)

1) file->new->other, the template list is displayed.

2 Select Java->enum on the template list and click the Next button

3 fill in each of the following fields according to Figure 1:

  Figure 1:eclipse 3.1 enum type create template

4 Click the Finish button to generate the priority class (definition???) and declare each value of priority as shown in Figure 2 below: (High, Medium, where does low come from???)

  Figure 2: Enumeration type priority

When creating an enumeration type, pay attention to several important concepts.

All of the enumerated types created are extended to java.lang.Enum. An enum is a new class defined in J2SE 5.0, which itself is not an enumeration type. When you create an enumeration type, you must use the Enum keyword to create an enumeration type without directly defining a class that inherits the enum, although all the enumerated types created are actually subclasses of the enum. If you inherit an enum directly, compiler will complain (causing a compilation error). As shown in Figure 3

Figure 3. Direct inheritance of the Enum class

Each value defined in an enumeration type is an instance of an enumeration type, for example, High is an instance of priority. An enumeration type is extended to an enum. Therefore, when each value declaration of an enumeration type is declared, the default is mapped to the enum (String name, int ordinal) constructor. In other words, the implementation of the enum Priority {high, Medium, and Low} calls the following enum constructor: The constructor call in Listing 2 mapping


New enum< Priority > ("High", 0);
New enum< Priority > ("Medium", 1);
New enum< Priority > ("Low", 2);

Each enumerated type created is a subclass of an enum. In addition to the constructor that invokes the parent Enum, the enumeration type can use parameters to define some of its own constructors. When declaring a value, you simply invoke the constructor defined by this enumeration type, and you do not have to add the New keyword. In Listing 3, An instance of Priority is generated, and this example is high (38).
Listing 3. Other constructor calls


Enum Priority {
High (38),
Medium (36.5),
Low (5.2);
Double temperature;
Priority (double p)
temperature = p;
}

Also two points to emphasize: one is that the constructors of these enumerated types are private. It cannot be invoked by other classes or other enumerated types. And this private modifier is automatically added by the compiler, and if we define these constructors, the previous addition of the public modifier will result in a compilation error, as shown in Figure 5 below. The second is that the variable definition must be after enumerating the type value definitions. The double temperature in the figure must be defined in the enumeration type value (the semicolon indicates that the enumeration type value is defined, such as low (5.2);) To declare.

Figure 4 The constructor for the enumeration type is private

Before J2SE 5.0, when we implement an enumeration class, we typically associate an integer with the name of a value of this enumeration class, and the problem is that the same integer can represent the values of different enumeration classes. The following example defines two enumerated classes Course and Grade as follows:
Listing 4.


public class Course {
public static final int englishlit = 1;
public static final int calculus = 2;
public static final int musictheory = 3;
public static final int musicperformance = 4;
}
public class Grade {
public static final int A = 1;
public static final int B = 2;
public static final int C = 3;
public static final int D = 4;
public static final int F = 5;
public static final int incomplete = 6;
}

If the developer mistakenly writes Student1.assigngrade (GRADE.A) as Student1.assigngrade (course.englishlist); Problems cannot be discovered during the compile phase, and can be avoided if the J2SE 5.0 enumeration type (enum) is used. Enumeration types Each value is public, static, and final. That is, these values are unique and once defined, they cannot be overridden or modified. And although the static keyword is not present when the enumeration type is declared for each value, the value is actually static. And we can't add static to the value, public,final modifier, or we'll get the error in Figure 6 below.

Figure 5 Error declaration for enumerated type values

Enumeration types implement Java.lang.Comparable, and the values of enumerated types can be sorted by comparison, in the order in which enumerated types define these values.

1.3 Application of enumeration types

The following subsections describe the various applications of enumeration types.

1.3.1 Cycle (iteration)

When we write a program, we often encounter situations in which each object in an array or list is processed. Before J2SE 5.0, if you want to do rounds in a series of arrays or lists, we do a lot of tedious work, and we need to use the Java.util.Iterator class as follows:

  Listing 5:


List priorities = Priority.values ().;
for (Iterator iter = Priorities.iterator (); Iter.hasnext ();) {
Priority p = (Priority) iter.next ();
Process (p);
}

Now we can use the J2SE 5.0 for/in loop and enum type together. This simplifies the process that has been spent a lot of time writing, as the program in Listing 5 above can be simplified to:

  Listing 6:


For (Priority g:priority.values ()) {
Process (g);
}

We run the above pseudocode as a program on the Eclipse3.1, as shown in the following illustration, showing the results of the operation in the lower-right control platform view. If the control platform is not visible, click Window->other views->console, the control platform will appear in the lower right corner .

  Figure 6 Application of enumerated types in loops

When we use the for/in loop, we require that its expression requirements must be an array or a collection of java.lang.Iterable, whereas the values () function of the enumerated type returns an array. The declaration of the loop variable must be in the loop, Include variable type and variable name.

We cannot use a variable declared outside of a loop in a loop. This differs from the declaration of the loop variable used in the J2SE 5.0 for loop.

1.3.2 Conversion (switch)

One of our common judgment statements is the Switch-case statement. Using an enumeration type in a switch statement not only simplifies the program, but also enhances the readability of the program.

  Listing 8.


File1:Task.java
public class Task {
Priority mypriority;
Public Task (Priority p) {
Mypriority=p;
}
Public Priority getpriority () {
return mypriority;
}}

File2:TestSwitch.java
public Class Testswitch (
Task task = new Task (priority.medium);
Switch (task.getpriority ()) {
Case High:
What's high
Break
Case Midum://Fall through
Case Low:
Do case Low
Break
Default:throw new Assertionerror ("Unexpected enumerated value!");
}
}

When you use an enumeration type in a switch statement, you must not precede each enumerated type value with the class name of the enumerated type, or the compiler will complain (causing a compilation error). We modified the above program slightly, adding the class name of the enumerated type in the case statement and running on the Eclipse 3.1 platform. We found that in Eclipse's problem view it is wrong to prompt the class name of the enumerated type in the case statement preceded by the enumeration type value, as shown in Figure 8 below.

Figure 7:case The value of the enumerated type in the statement

The reason is that the implementation of J2SE 5.0 requires that each enumerated type value in the case statement cannot be prefixed with an enumerated type class. The value of each enumerated type is an instance of an enumeration type. So when the compiler compiles the case statements, how do you handle them? There are two scenarios: if the switch is defined in the same compilation unit as the enumeration type, a new table is created in memory the first time it is compiled. In this table, the values of each enumerated type are associated with the order in which it is defined in the enumeration type. Compiler compilation results are similar to the programs shown in Listing 9 below. But the sequence number is not added to the program, but the compiler in the table quickly query. If the enumeration type is modified or defined, the table is updated.

Listing 9:


public Class Testswitch (
Task task = new Task ();
Switch (task.getpriority ()) {
Case 0:
What's high
Break
Case 1://fall through to low
Case 2:
Do case Low
Break
Default:throw new Assertionerror ("Unexpected enumerated value!");
}
}

Another common occurrence is that the switch is not defined in the same compilation unit as the enumeration type. In this case, most compilers translate the Switch-case statement into a series of if/else statements:

list:


Priority tmp = task.getpriority ();
if (TMP = = high)
What's high
else if (tmp = = Midium)
else if (tmp = = low)
Do case Low
else {
throw new Assertionerror ("Unexpected enumerated value!");
}

1.3.3 Maps of enum and Sets of enum

Two new classes are available in the Java.util package in J2SE 5.0: Enummap and Enumset, and the combination of these two classes with enumerated types makes it easy to use previously cumbersome procedures. The Enummap class provides a special implementation of the Java.util.Map interface, in which the keys (key) is an enumerated type.

  Listing 11:. Enummap Example


public void Test () throws IOException {
Enummap<priority, string> descriptionmessages =
New enummap< Priority, string> (Priority.class);
Descriptionmessages.put (Priority.high, "high means ...");
Descriptionmessages.put (Priority.medium, "Medium represents ...");
Descriptionmessages.put (Priority.low, "low means ...");
For (Priority p:priority.values ()) {
System.out.println ("for priority" + P +), Decription is: "+
Descriptionmessages.get (p));
}
}

The Enumset class provides an implementation of the Java.util.Set interface, which holds a collection of values for some type of enumeration. Enumset acts like a collection of attributes or a subset of the values of all elements of an enumeration type. The Enumset class has a series of static methods that you can use to get a single element or some element from an enumeration type, and the following program example shows how these static methods are:

  Listing 12:. Enumset Example

 
public class Testenumset { 
public enum colorfeature { 
RED , BLUE, GREEN, yellow,black 
}; 
public static void Main (string[] args) { 
Enumset Allfeatur Es = Enumset.allof (colorfeature.class); 
Enumset warmcolorfeatures = enumset.of (colorfeature.red, 
Colorfeature.yellow); 
Enumset non_warmcolorfeatures = Enumset.complementof (warmcolorfeatures); 
Enumset notblack = Enumset.range (colorfeature.red, Colorfeature.yellow); 

for (colorfeature CF: Colorfeature.values ()) { 
if (warmcolorfeatures.contains (CF)) { 
System.out.println ("Warmcolor" + Cf.name ()); 

if (non_warmcolorfeatures.contains (CF)) { 
System.out.println ("Non_ Warmcolor "+cf.name ()); 



Related Article

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.