Use the j2se 5.0 Enumeration type in eclipse3.1

Source: Internet
Author: User
Tags case statement
This article introduces three important features of j2se 5.0: Enumeration type, annotation type, and paradigm. On this basis, it introduces how to develop enumeration types in the eclipse 3.1 development environment, annotation type and fan type applications.

The release of j2se 5.0 (TIGER) is an important milestone in the development history of Java language and the greatest progress made so far in Java programming.

J2se 5.0 provides many exciting features. these features include support for general, enumeration, metadata, unboxing, and autoboxing ), varargs, static imports, and thread framework ).

With the release of j2se 5.0, more and more integrated development environments (IDES) Support j2se 5.0 development. the famous open-source Java ide eclipse has supported j2se 5.0 development since 3.1m4. The latest version is 3.1rc4.

This series will introduce three important features of j2se 5.0: Enumeration type, annotation type, and fan type. On this basis, we will introduce how to develop enumeration types in the eclipse 3.1 development environment, annotation type and model application. this topic describes enumeration types.

1. Enumeration type

1.1 Enumeration type

J2se 5.0 and the previous JDK have two basic methods to define a new type: classes and interface. for most object-oriented programming, these two methods seem sufficient. however, in some special cases, these methods are not suitable. for example, we want to define a type of priority, which can only accept three values: High, Medium, and low. any other value is invalid. JDK before j2se 5.0 can construct this type, but a lot of work is required, which may lead to insecure (type security problems ???) And other potential problems, and j2se 5.0 Enumeration type (Enum) can avoid these problems.

Eclipse is the most common development platform for Java programmers, and eclipse 3.1 provides support for j2se 5.0, which provides a help tool for new j2se 5.0 features. with support for enumeration types, it not only provides creation templates for enumeration types, but also provides error prompts and help for various development errors of enumeration types.

This article first introduces the basic concepts for creating enumeration types and how to create enumeration types on the eclipse 3.1 platform. Then, we use examples in the eclipse 3.1 Development Environment to illustrate the application of enumeration types.

1.2 create an enumeration type

The following example shows how to create a 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 the steps below to generate an enumeration type: (eclipse 3.1 provides a new Wizard for creating enumeration types (wizard) to facilitate the creation of enumeration types)

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

2) Select Java> Enum in the template list and click Next.

3) Fill in the following fields as shown in Figure 1:

  Figure 1: Eclipse 3.1 Enumeration type creation Template

4) Click the finish button to generate the priority class (definition ???), And declare each value of priority, as shown in Figure 2: (high, medium, where does low come from ???)

  Figure 2: Enumeration type priority

Pay attention to several important concepts when creating enumeration types.

  • All created enumeration types are extended to Java. lang. enum. enum is a new class defined in j2se 5.0. It is not an enumeration type. when creating an enumeration type, you must use the enum keyword. You cannot directly define a class that inherits Enum to create an enumeration type, even though all created enumeration types are actually subclasses of enum. if the enum is inherited directly, compiler reports an error (which may cause compilation errors ). 3.

    Figure 3. inherit the enum class directly

  • Each value defined in The Enumeration type is an instance of the enumeration type. For example, high is an instance of priority. the enumerated type is also extended to enum. therefore, when each value of the enumeration type is declared, it is mapped to the enum (string name, int ordinal) constructor by default. in other words, the implementation of Enum priority {High, Medium, Low} is to call the following Enum constructor:

    List 2 ing constructor call


       new Enum< Priority >("High", 0);   new Enum< Priority >("Medium", 1);   new Enum< Priority >("Low", 2); 

    Each created Enumeration type is a subclass of enum. Apart from calling the constructor of the parent class Enum above, enumeration types can use parameters to define some of their own constructors. when declaring a value, you only need to call the constructor defined for this enumeration type and do not need to add the new keyword. in listing 3, a priority instance is generated, and this instance 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;    } 

    The following two points should be emphasized: first, all enumeration constructors are private. it cannot be called by other classes or other enumeration types. this private modifier is automatically added by the compiler. If we add a public modifier to the constructor when defining these constructor functions, it will cause compilation errors, as shown in Figure 5. second, the variable must be defined after the enumerated type value. double temperature can be declared only after the enumerated type value is defined (semicolon indicates that the enumerated type value is defined, for example, low (5.2.

    Figure 4. Enumeration constructors are private

  • Before j2se 5.0, when we implement an enumeration class, we generally associate an integer with the name of a value of this enumeration class, the problem is that the same integer can represent the values of different enumeration classes. the following example defines two enumeration 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 calls student1.assigngrade (grade. a) written as student1.assigngrade (course. englishlist); problems cannot be found in the compilation phase. If j2se 5.0 Enumeration type (Enum) is used, these problems can be avoided.

  • Each value of the enumeration type is public, static, and final. that is to say, these values are unique and cannot be overwritten or modified once defined. in addition, although there is no static keyword in each value declaration of the enumeration type, the values are actually static, and we cannot add static, public, final modifiers before the values, otherwise, a 6 error occurs.

    Figure 5 Enumeration type value error Declaration

  • Java. Lang. Comparable is implemented for the enumeration type. Values of the enumeration type can be sorted by comparison. The sorting order is the order in which the enumeration type defines these values.

1.3 Enumeration type applications

The following sections describe various enumeration applications.

  1.3.1 Loop)

When writing a program, we often encounter processing every object in an array or list. before j2se 5.0, if we want to perform round robin in an array or list, our approach is cumbersome and requires the help of Java. util. the iterator class is 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 for/in loop of j2se 5.0 together with the enumeration type, which simplifies the program that previously spent a lot of time writing. For example, the program in listing 5 can be simplified:

  Listing 6:

 for (Priority g: Priority.values()){  process(g); } 

The preceding pseudo code is written to run on eclipse3.1, as shown in. The running result is displayed in the lower right control platform view. if you cannot see the control platform, click WINDOW> other views> console. The control platform appears in the lower right corner.

  Figure 6 Application of Enumeration type in Loops

When we use for/in loop, the expression must be an array or Java. lang. iterable, and the values () function of Enumeration type returns an array. in addition, the Circular Variable Declaration must be in the loop, including the variable type and variable name.

We cannot use a variable declared outside the loop in the loop. This is different from the declaration of the loop variable used in the for loop before j2se 5.0.

1.3.2 Switch)

One of our commonly used judgment statements is the switch-case statement. Using the enumeration type in the 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:       //do case High              break;        case Midum: // fall through to Low        case Low:       //do case Low              break; default: throw new AssertionError("Unexpected enumerated value!");        }    } 

When an enumeration type is used in a switch statement, the Class Name of the enumeration type cannot be added before each Enumeration type value; otherwise, the compiler reports an error (which may cause compilation errors ). we will slightly modify the above program, add the enumerated class name in the case statement, and run it on the eclipse 3.1 platform. in the eclipse problem view, we found that it is incorrect to add the enumeration class name before the enumeration type value in the case statement, as shown in figure 8.

Figure 7: Enumeration type values in the case statement

The reason is that j2se 5.0 requires that each Enumeration type value in the case statement cannot have an enumeration type class as the prefix. we have mentioned that values of each Enumeration type are an instance of the enumeration type. so how does the compiler handle these instances when compiling case statements? There are two cases: if the switch and enumeration type are defined in the same compilation unit, a new table will be created in the memory during the first compilation. in this table, the values of each Enumeration type are associated with the order defined in the enumeration type. the compiler compilation result is similar to the program shown in listing 9 below. however, the sequence number is not added to the program, but is quickly queried by the compiler in the table. if the enumeration type is modified or the definition is defined, the table is updated.

Listing 9:

 public class TestSwitch (    Task task = new Task();    switch (task.getPriority( )) { case 0:       //do case High              break;        case 1: // fall through to Low        case 2:       //do case Low              break; default: throw new AssertionError("Unexpected enumerated value!");        }    } 

Another common case is that the switch and enumeration type definition are not in the same compilation unit. in this case, most compilers translate the switch-case statement into a series of IF/else statements:

Listing 10:

 Priority tmp = task.getPriority( ); if (tmp == High)  //do case 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

In j2se 5.0 Java. the util package provides two new classes: enummap and enumset. The combination of these two classes and enumeration types can simplify and simplify previously cumbersome programs. the enummap class provides Java. util. A special implementation of the map interface. The key in this interface is an enumeration 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 Java. util. set interface, which stores a set of enumerated values. the enumset function is similar to a set of features or a subset of values of all elements of an enumeration type. the enumset class has a series of static methods that can be used to obtain a single element or some elements from the enumeration type. 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 allFeatures = 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());       }        }  } }  

Run the above program in eclipse3.1. The result is as follows:

  Figure 8: enumset sample running result

1.3.4 Function Definition of Enumeration type

In this section, we mentioned that all enumeration types are Java. lang. subclass of enum. that is to say, all enumeration types are compiled Java classes, so you can add constructors and other functions to the enumeration types, such as getdescription () in listing 13 ()

  Listing 13:

         public enum ColorFeature {   RED(0),           BLUE(0),           GREEN(300),         YELLOW(0),   BLACK(0);                 /** The degree for each kind of color*/        private int degree;        ColorFeatures(int degree) {           this.degree = degree;        }        public int getDegree( ) {             return degree;        }         public String getDescription( ) {             switch(this) { case RED:       return "the color is red";   case BLUE:      return "the color is blue";                 case GREEN:     return "the color is green";                   case BLACK:     return "the color is black";                       case YELLOW:    return "the color is yellow"                       default:        return "Unknown Color";             }         }}         

The Application of enumeration function definition is very useful. For example, you can implement the same interface for multiple enumeration types to achieve programming model. for example, an interface that defines the getdescription () interface allows different enumeration types with the same requirements to implement it. the colorfeature above can be implemented, and the other fontfeature can also be implemented.

1.3.5 constants-specific class subjects

In the previous section, we mentioned that enumeration types can define their own functions. In fact, further, every value of enumeration types can implement Abstract Functions Defined in enumeration types. This sounds incredible, let's take a look at the example below.

 public enum Priority implements Feature {    High (38) {       public void perform() {             System.out.println("high 38");         }        },     Medium(36.5) {      public void perform() {             System.out.println("medium 36.5");         }     },     Low (5.2){      public void perform() {             System.out.println("low 5.2");         }     };     public abstract void perform();     public String getDescription(Priority p) {      return null;     }  } 

The enumeration type priority defines an abstract function perform (). Each value of priority is overloaded with the perform function, which is the class entity of the enumeration type specific to constants. in this case, each declared value is generated by a subclass of the enumeration type, and a unique instance of this subclass is generated to represent this value. different values have different subclasses. each subclass can overload the Abstract Functions of the parent class. we can run the following program in eclipse3.1 to prove that the three subclasses are generated at this time.

 public class Task {     Priority myPriority; public Task (Priority p) {   myPriority=p; } public Priority getPriority(){  return myPriority; } public void test() throws IOException {  if (myPriority == Priority.High)         System.out.println(Priority.High.getClass().getName());        if (myPriority == Priority.Medium)         System.out.println(Priority.Medium.getClass().getName());     if (myPriority == Priority.Low)          System.out.println(Priority.Low.getClass().getName()); }} public class TestSwitch {     public static void main(String[] args) {         Task task = new Task(Priority.High);  Task task1 = new Task(Priority.Medium);  Task task2 = new Task(Priority.Low);  try {  task.test();  task1.test();  task2.test();  } catch (IOException e) {  e.printStackTrace();  }  } 

The running result is as follows: 10.

  Figure 9 test the running result of a constant-specific class subject

Because the classes specific to constants are difficult to understand and prone to errors, they are rarely used. In most cases, they can be replaced by the switch-case statement. This is a brief introduction here for your reference only.

1.4 Summary of enumeration types

It is very easy to use the enumeration type. it defines a fixed and closed set of values. When a value is required, it can be specified by its name, which is the simplicity of the enumeration type. the value of the enumeration type is an instance of the enumeration type. The compiler will ensure that no other types are passed in, which is the security of the enumeration type. these enumeration types are the classes themselves. Therefore, all operations that can be performed on the classes can also be applied to the enumeration types. we should be careful to use constructors and function overload methods, and do not use them as they are available. for example, a constant-specific class entity can be replaced by a switch statement in most cases, which is easier to understand and error-prone. we also saw support for enumeration types on the eclipse 3.1 platform, including providing creation templates and error message prompts. in short, the flexible application of Enumeration type can greatly facilitate and simplify our development work.

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.