An important new feature in tiger is enumeration structure, which is a new type that allows constants to represent specific data fragments, and all of them are expressed in type-safe form. Brett McLaughlin, a tiger expert and productivity author on developerworks, will explain the definition of enumeration and explain how to apply Program Use enumeration and why it allows you to discard all old
Public static final
Code .
As you know, the two basic construction blocks of Java code areClassAndInterface. Now tiger introducesEnumeration, Generally referred toEnum. This new type allows you to represent specific data points. These data points only accept pre-defined Value Sets during allocation.
Of course, skilled programmers can use static constants to implement this function, as shown in Listing 1:
Listing 1. constants of public static final
Public class oldgrade {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 ;}
|
Note:I would like to thank o'reilly media, which allows me to use what I wrote in this articleJava 1.5 Tiger: A developer's notebookCode examples in the "enumeration" section in this book (see references ).
Then you can make the class accept the imageOldgrade. B
Such constants, but remember that these constants are in JavaInt
Type constant, which means the method can accept anyIntType value, even if it andOldgrade
All levels defined in. Therefore, you need to check the upper and lower bounds. When an invalid value occurs, it may containIllegalargumentexception
. In addition, if you add another level (for exampleOldgrade. withdrew_passing
), You must change the upper bound of all codes to accept the new value.
In other words, this solution may be feasible when you use a class with an integer constant, but it is not very effective. Fortunately, enumeration provides a better method.
Define Enumeration
Listing 2 uses an enumeration that provides features similar to listing 1:
Listing 2. simple enumeration types
Package com. oreilly. Tiger. ch03; Public Enum grade {A, B, C, D, F, incomplete };
|
Here, I use a New KeywordEnum
To provide a name for Enum and specify the allowed values. Then,Grade
It becomesEnumeration type, You can use it as shown in listing 3:
Listing 3. Using enumeration types
package COM. oreilly. tiger. ch03; public class student {private string firstname; private string lastname; private Grade; Public student (string firstname, string lastname) {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 (firstname ). append (""). append (lastname ). tostring ();} public void assigngrade (Grade) {This. grade = Grade ;}public grade getgrade () {return grade ;} |
Create a new enumeration with the previously defined type (Grade
), You can use it like other member variables. Of course, enumeration can only be assigned one of the enumerated values (for example,A
,C
OrIncomplete
). In additionAssigngrade ()
There is no code for error detection, and the boundary is not considered. Please note how this is done.
Use enumeration values
The examples you have seen so far are quite simple, but the enumeration type provides more than that. You can traverse the enumerated values one by one, orSwitch
Use enumeration values in a statement. enumeration is very valuable.
Enumerate values
The following example shows how to traverse enumerated values. This technology, as shown in Listing 4, applies to debugging, fast printing tasks, and loading enumeration into collections (I will talk about it soon:
Listing 4. traversing enumerated values
Public void listgradevalues (printstream out) throws ioexception {for (grade G: grade. values () {out. println ("allowed value: '" + G + "'");}}
|
Run this code and you will get the output shown in listing 5:
Listing 5. Output of iterative operations
Allowed value: 'A' allowed value: 'B' allowed value: 'C' allowed value: 'D' allowed value: 'F' allowed value: 'complete'
|
There are many things here. First, I used the new tigerFor/in
Loop (also calledForeach
OrEnhanced
). In addition, you can seeValues ()
Method returns an independentGrade
An array composed of instances. Each array has an enumerated value. In other words,Values ()
The returned value isGrade []
.
Switch between Enumeration
The ability to move between enumerated values is good, but more importantly, the decision is made based on enumerated values. You can write a bunchIf (grade. Equals (grade. ))
Type statement, but it is a waste of time. Tiger can easily add enumeration support to the past.Switch
Statement, so it is easy to use and suitable for what you know. Listing 6 shows how to solve this problem:
Listing 6. switching between Enumeration
Public void testswitchstatement (printstream out) throws ioexception {stringbuffer outputtext = new stringbuffer (student1.getfullname (); Switch (student1.getgrade () {Case: outputtext. append ("excelled with a grade of a"); break; Case B: // fall through to c Case C: outputtext. append ("passed with a grade "). append (student1.getgrade (). tostring (); break; Case D: // fall through to f Case F: outputtext. append ("failed with a grade "). append (student1.getgrade (). tostring (); break; Case incomplete: outputtext. append ("did not complete the class. "); break;} Out. println (outputtext. tostring () ;} |
Here, the enumerated value is passedSwitch
Statement (Remember,Getgrade ()
YesGrade
), And eachCase
Clause will process a specific value. This value does not have an enumeration prefix when it is provided, which means you do not need to write the codeCase grade.
, You only need to write itCase
You can. If you do not do this, the compiler will not accept values with a prefix.
Now you should know how to useSwitch
The basic syntax of the statement, but you need to know something else.
Schedule before using the switch
As you expected, you can useDefault
Statement. Listing 7 shows the usage:
Listing 7. Add a default Block
Public void testswitchstatement (printstream out) throws ioexception {stringbuffer outputtext = new stringbuffer (student1.getfullname (); Switch (student1.getgrade () {Case: outputtext. append ("excelled with a grade of a"); break; Case B: // fall through to c Case C: outputtext. append ("passed with a grade "). append (student1.getgrade (). tostring (); break; Case D: // fall through to f Case F: outputtext. append ("failed with a grade "). append (student1.getgrade (). tostring (); break; Case incomplete: outputtext. append ("did not complete the class. "); break; default: outputtext. append ("has a grade "). append (student1.getgrade (). tostring (); break; } Out. println (outputtext. tostring () ;} |
The code above shows that nothing isCase
The enumerated values processed by the statement areDefault
Statement processing. You shallPersistence. The reason is: assumeGrade
Enumeration is modified by other programmers in your group (and he forgot to tell you about it) into the version shown in listing 8:
Listing 8. Add a value to the grade Enumeration
Package com. oreilly. Tiger. ch03; Public Enum grade {A, B, C, D, F, incomplete, Withdrew_passing, withdrew_failing};
|
Now, if you use the new version shown in the code in Listing 6Grade
The two new values are ignored. Worse, you can't even see the error! In this case, some commonDefault
Statements are very important. Listing 7 cannot process these values well, but it will prompt you that there are other values that you need to process. Once the processing is completed, you will have an application that continues to run, and it will not ignore these values, or even guide you in the next step. So this is a good coding habit.
Enumeration and set
Usage you are familiarPublic static final
The enumerated value may have been used as the ing key. If you do not know the meaning, refer to listing 9, which is an example of a public error message. When using the ant Build File, such a message may pop up, as shown below:
Listing 9. Ant status code
Package com. oreilly. Tiger. ch03; Public Enum antstatus {initializing, compiling, copying, jarring, zipping, done, error}
|
Assign some error messages that people can understand to each status code, so that people can find the appropriate error information when ant provides a code and display the information on the console. This isMap)
Here, eachMap)
The key is an enumerated value, and each value is a key error message. Listing 10 demonstrates how the ing works:
Listing 10. Enumeration ing (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 the generic (generics) (see references) and the newEnummap
Create a new ing. In addition, the enumerated value isClass
Objects are provided, and the type of the ing value is also provided (in this example, it is just a simple string ). The output of this method is shown in listing 11:
Enumeration class object? You may have noticed that the sample code in listing 10 actually indicates that tiger treats enumeration as a class.Antstatus OfClass The object proves that the object is not only available, but also being used. This is true. In the final analysis, tiger still regards enumeration as a special class type. For more information about how to implement enumeration, seeJava 5.0 Tiger: A developer's notebook(See references ). |
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 complete. [Java] for status error, message is: error occurred.
|
Further steps
Enumeration can also be used in combination with a set, and is very similar to the newEnummap
Structure, Tiger provides a new setEnumset
To allow you to use bitwise operators. In addition, you can add methods for enumeration and use them to implement interfaces, which are definedObject of a class with a specific valueIn this object, the specific code is appended to the specific value of the enumeration. These features are beyond the scope of this article, but there are other documents that detail them (see references ).
Use enumeration, but do not abuse
One danger of learning any new version of the language is the crazy use of the new syntax structure. If you do this, 80% of your code will suddenly be generic, annotation, and enumeration. Therefore, it should be used only when enumeration is applicable. So where does enumeration apply? A general rule is that any place where constants are used, such as currently usedSwitch
The place where the code switches constants. If there is only one value (for example, the maximum size of a shoe or the maximum number of monkeys in a cage), leave this task to a constant. However, if you define a set of values, and any of these values can be used for a specific data type, it is best to use enumeration in this place.
References
- For more information, see the original article on the developerworks global site.
- download tiger and try it on your own.
- the official j2se 5.0 home page is a comprehensive resource that you cannot omit.
- for more information about Tiger, see taming tiger series of articles , A brief prompt is provided for the new content and changed content in j2se 5.0.
- Brett McLaughlin also wrote two series of articles on tiger labeling: annotations in tiger, Part 1: add metadata and annotations in tiger to Java code, Part 2: custom comments.
- JAVA 1.5 Tiger: A developer's notebook (O 'Reilly & Associates; 2004) by Brett McLaughlin and David Flanagan, this book introduces almost all the latest tiger features (including tagging). The format of this book is code-centric and applies to developers.
- In the developerworks JAVA technology area, you can find hundreds of articles on various aspects of Java programming.
- visit the developer bookstore to obtain a complete list of technical books, including hundreds of books on Java-related topics.
About the author Brett McLaughlin from the logo age (Do you remember that little triangle ?) He started to work on computers and at companies like Nextel communications and lutris technologies. In recent years, he has become one of the most well-known authors and programmers in the Java and XML communities. His new bookJava 1.5 Tiger: A developer's notebookIs the first reference book on the new version of Java technology, classic masterpieceJava and XML |