Enumeration Type Getting Started (Reprinted from IBM Developer)

xiaoxiao2021-03-06  67

An important new feature in TiGer is an enumeration structure, which is a new type that allows specific data pieces to represent a specific data segment, and all are represented in terms of type security. Tiger expert, developerWorks's multi-producer Brett McLaghlin explains the definition of enumeration, introduces how to use enumeration in the application, and why can it let you abandon all old public static final code. You already know that two basic structural blocks of Java code are classes and interfaces. Now Tiger introduces enumeration, generally referred to as ENUM. This new type allows you to represent a specific data point, which only accepts the pre-defined value collection when allocation.

Of course, skilled programmers can achieve this function with static constants, as shown in Listing:

Listing 1. Confringes of Public Static Final

Public class oldgrade {

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;}

Note: I would like to thank O'Reilly Media Company, which allows the use of the Java 1.5 Tiger: A Developer's Notebook book in this article (see Refer to the reference).

You can then allow the class to accept constants like Oldgrade.b, but when doing this, remember that this type of constant is the constant of int type in Java, which means that the method can accept any Int type value, even It does not correspond to all levels defined in Oldgrade. Therefore, you need to detect the upper and lower bounds. When there is an invalid value, you may have an IllegaLaRgumentException. Moreover, if you later add another level (for example, Oldgrade.withDrew_Passing, you must change the upper bound in all code to accept this new value.

In other words, the solution may be feasible when using such a class with integer constant, but is not very effective. Fortunately, the enumeration provides a better way.

Definition enumeration list 2 Using a enumeration that can provide a function similar to the list 1:

Listing 2. Simple enumeration type

Package com.ioLly.tiger.ch03;

Public enum grade {a, b, c, d, f, incomplete};

Here, I used a new keyword ENUM that provided a name for Enum and specified the allowed value. Then, Grade becomes an enumeration type, you can use it by the method shown in Listing 3:

Listing 3. Use enumeration type

Package com.ioLly.tiger.ch03;

Public class student {

Private string firstname; private string lastname; private grade grade;

Public student (String firstname) {this.firstname = firstname; this.lastname = lastname;}

Public void setfirstname (String firstname) {this.firstname = firstname;} public string getfirstname () {return firstname;}

Public void setlastname (String lastname) {this.lastname = lastname;

Public string getlastname () {return Lastname;}

Public String getFullName () {Return New StringBuffer ("") .append (Lastname) .tostring ();

Public void assigngrade (grade grade) {this.grade = grade;}

Public grade getGrade () {return grade;}}

After establishing a new enumeration (Grade) with previously defined types, you can use it like other member variables. Of course, enumerating only one of the enumerated values ​​(eg, A, C or Incomplete) can only be assigned. Moreover, in AssignGrade (), there is no error detected code, nor does it consider the boundary condition, please pay attention to how this is done.

Using enumeration values ​​so far, the examples you have seen are quite simple, but the enumeration type is far more than this. You can traverse enumeration values ​​one by one, or you can use enumeration values ​​in the Switch statement, and the enumeration is very valuable.

Traverse Enumeration Value Let's display how to traverse enumeration types in one example. The technology shown in Listing 4 applies to commissioning, quick print tasks and putting enumerations to a collection (I will talk quickly):

Listing 4. Traverse enumeration value

Public void ListGradeValues ​​(PrintStream out) throws oException {for ()) {Out.println ("Allowed Value: '" G "");}}

Run this code, will get the output shown in Listing 5:

Listing 5. Output of iterative operations

Allowed value: 'aallowed value:' c'allowed value: 'd'allowed value:' F'allowed value: 'Incomplete'

There are many things here. First, I used Tiger's new FOR / IN loop (also called Foreach or enhanced for). Alternatively, you can see that the value of the VALUES () method returns an array consisting of a stand-alone Grade instance, each array has an enumerated value. In other words, the return value of VALUES () is grade [].

Switching between enumerations is moving well between the values ​​of the enumeration, but more important is based on the value of the enumeration. You can of course write a bunch of IF (Grade.equals (grade.a)) type statement, but that is wasting time. Tiger can easily add enumeration support to the past good Switch statement, so it is easy to use, and it is suitable for you know. Listing 6 will show how to solve this problem: Listing 6. Switch between enumerations

Public void testswitchstatement (PrintStream out) throws ioException {stringbuffer outputtext = new stringbuffer ());

Switch (student1.getgrade ()) {CASE A: OutputText.Append ("Excelled with a grade of a"); Break; Case B: // Fall THROUGH TO C CASE C: OutputText.Append ("Passed with a grade of ") .Append (student1.getgrade (). Tostring ()); break; case d: // Fall Through to f Case F: OutputText.Append (" Failed with a grade of ") .append (student1.getgrade () .tostring ()); Break; Case INCOMPLETE: OUTPUTTEXT.APpend ("DID NOT COMPLETE THE CLASS.");

Out.println (outputText.toString ());

Here, the enumeration value is passed to the Switch statement (remember, getgrade () is returned as an instance of grade), and each CASE clause will process a specific value. This value does not have an enumeration prefix when providing, means that you don't have to write the code as Case Grade.a, just write it into Case A. If you don't do this, the compiler does not accept the value with a prefix.

Now, you should have already understood the basic syntax when using the Switch statement, but there are some things you need to know. Make a plan before using Switch, you can use the default statement when you use the enumeration and Switch. Listing 7 shows this usage:

Listing 7. Add a Default block

Public void testswitchstatement (PrintStream out) throws ioException {stringbuffer outputtext = new stringbuffer ());

Switch (student1.getgrade ()) {CASE A: OutputText.Append ("Excelled with a grade of a"); Break; Case B: // Fall THROUGH TO C CASE C: OutputText.Append ("Passed with a grade of ") .Append (student1.getgrade (). Tostring ()); break; case d: // Fall Through to f Case F: OutputText.Append (" Failed with a grade of ") .append (student1.getgrade () .tostring ()); Break; Case INCOMPLETE: OUTPUTTEXT.APpend ("DID NOTETETE THE CLASS."); Break; Default: OutputText.Append ("HAS a grade of") .append (student1.getgrade (). Tostring ()); Break;} out.println (outputText.toString ());

It can be seen that the above code can be seen that any enumerated values ​​that are not processed by the CASE statement will be processed by the default statement. You should adhere to this technology. The reason is: Suppose Grade enumerates the version of other programmers in your group (and he forgot to tell you this) to the version shown in Listing 8:

Listing 8. Add a value to your grade enumeration

Package com.ioLly.tiger.ch03;

Public Enum grade {A, B, C, D, F, Incomplete, Withdrew_Passing, Withdrew_failing};

Now, if the new version shown in Listing 6 is used, then the two new values ​​will be ignored. Worse, you can't even see the mistake! In this case, there is a very important default statement that can be universal. Listing 7 cannot handle these values ​​well, but it will prompt you to have other values, you need to handle these values. Once processed, you will have an application that continues to run, and it will not ignore these values, and even guides you the next action. So this is a good coding habit.

Enumerates and gather Things that you are familiar with the use of the Public Static Final method, may have turned to use the enumerated value as a mapping key. If you don't know the meaning, see Listing 9. It is an example of a public error message. When using an Ant's build file, you may pop up such a message, as shown below:

Listing 9. ANT status code

Package com.ioLly.tiger.ch03;

Public Enum Antstatus {Initializing, Compiling, Copying, Jarring, Zipping, Done, Error}

Assign some of the error messages that people can read for each status code, allowing people to find appropriate error messages when Ant provides a code, displaying this information on the console. This is an excellent use case of mapping (MAP), where each mapping (MAP) key is an enumeration value, and each value is an error message for the key. Listing 10 demonstrates the mapping mode: Listing 10. Map of enumeration (MAP)

public void testEnumMap (PrintStream out) throws IOException {// Create a map with the key and a String message EnumMap antMessages = new EnumMap (AntStatus.class);

// Initialize the map antMessages.put (AntStatus.INITIALIZING, "Initializing Ant ..."); antMessages.put (AntStatus.COMPILING, "Compiling Java classes ..."); antMessages.put (AntStatus.COPYING, "Copying Files ... "); AntMessages.Put (AntStatus.jarring," Jarring Up Files ... "); AntMessages.Put (AntStatus.zipping," Zipping Up Files ... "); AntMessages.put (Antstatus.done "Build Complete."); AntMessages.Put (AntStatus.Error, "Error Occurred.");

// Iterate and Print Messages for (AntStatus Status: antstatus.values ​​()) {Out.Println ("For Status" Status ", Message IS:" AntMessages.get (status));}}

This code uses generics (see Resources) and new ENUMMAP constructs to create new mappings. Moreover, the enumeration value is provided by its Class object, and the type provided also has the type of mapping value (in this case, it is just a simple string). The output of this method is shown in Listing 11:

Enumerate Class object? You may have noticed that the sample code in Listing 10 actually indicates that Tiger will be used as a class, which can be proved from the Class object of Antstatus, which is not only available, but is actually used. This is real. In the final analysis, Tiger still regards enumeration as a special class type. For details on the specific implementation details of enumeration, see Chapter 3 of Java 5.0 Tiger: Adeveloper's Notebook (see Resources).

Listing 11. Output of Listing 10

[Echo] Running AntStatusTester ... [java] For status INITIALIZING, message is: Initializing Ant ... [java] For status COMPILING, message is: Compiling Java classes ... [java] For status COPYING, message is: Copying Files ... [java] for status jarring, message is: jarring up files ... [java] for status zipping, Message IS: zipping up files ... [java] for status done, Message is: build completion. Further enumeration can also be used in conjunction with a collection, and a new EnumMap constructor is very like a new enummap configuration, which allows you to use the bit operator. Further, it is possible to add a method to an enumeration, and the interface is used to define an entity called a specific value, in which a particular code is attached to the specific value of the enumeration. These features exceed the scope of this article, but in other places, they have a detailed introduction to their documentation (see Resources).

Use enumeration, but do not abuse a danger of learning any new language is crazy to use new syntax structure. If this is done, your code will suddenly be 80% of generic, labeling and enumeration. Therefore, it should only be used only where it is suitable for use. So, where is the enumeration? A universal rule is where any constant is used, for example, where the constant is currently switched with the Switch code. If there is only a single value (for example, the biggest size of the shoes, or the maximum number of monkeys in the cage), then leave this task to constants. However, if a set of values ​​are defined, any of these values ​​can be used for a specific data type, then the enumeration is most suitable for this place.

Reference

You can see this article in our website on our world.

Download Tiger and try it yourself.

Official J2SE 5.0 Home Page is a comprehensive resource you cannot miss.

For specific contents of Tiger, see the Taming Tiger Series written by John Zukowski, which provides a short tip for new content and changes in the J2SE 5.0.

Brett McLaughlin has written two series of articles about Tiger: Note in Tiger, Part 1: Adding metadata to the Java code and comments in Tiger, Part 2: Custom comments.

Java 1.5 Tiger: A Developer's Notebook (O'Reilly & Associates; 2004) The author is Brett McLaughlin and David Flanagan, this book introduces the latest features of all Tiger (including labels), the book's format is core Suitable for developers.

In the developerWorks Java Technology area, you can find hundreds of articles about the Java programming.

Please visit developer bookstore to get a complete list of technical books, including hundreds of Java-related topics.

转载请注明原文地址:https://www.9cbs.com/read-84203.html

New Post(0)