Enumerated types entry java

  Abstract: java enumerated types entry 

  </ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td width="295" height="265" align="center" valign="top"> </ td> <td width="405" valign="top"> 

  Tiger in a major new features is the enumeration structure, it is a new type, allows constant for a specific fragment of data, and all types of security in the form of that.    Tiger experts, the prolific author developerWorks Brett McLaughlin will explain the definition of enumerated, in the application of procedures on how to use enumerated, as well as why is it that enables you to discard all the old 
  Public static final code. 

  You know, the Java code of the two basic building blocks that category and interfaces.    Now Tiger also introduced enumerated, it is generally referred enum.    This new type allows you to the particular data point, these data points will only accept distribution of pre-defined set of values. 

  Of course, skilled programmers static constants can be used to achieve this function, as shown in a list: 

  </ Td> </ tr> <tr> <td height="44" colspan="2"> 

  List 1. Public static final constants 

  (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 Corporation, which has allowed the use of paper I write the Java 1.5 Tiger: 
  A Developer's Notebook book "enumeration" of this chapter, the code examples (see references). 

  Then you can let this type OldGrade.B accepted as constants, but in doing so, please remember these constants 
  Int type in Java is the constant, which means that the method can accept any type of int values, and even if it 
  OldGrade in all levels are set counterparts.    Therefore, you need to detect the upper and lower bounds, in the event of invalid value, may also 
  To include an IllegalArgumentException.    Moreover, if the later add another level (for example, 
  OldGrade.WITHDREW_PASSING), then all the code must be changed in the sector, can accept the new value. 

  In other words, the use of such a type of integer constant, the solutions may be feasible, but not very effective.    Fortunately, 
  Win that the enumeration provided a better method. 

  Enumerating definition 
  List 2 can be used to provide a list of the functions of a similar enumeration: 

  List 2. Simple enumeration type 

  Package com.oreilly.tiger.ch03; 

  (Public enum Grade 
  A, B, C, D, F, INCOMPLETE 
  ); 

  Here, I use the new enum keyword for the enum provide a name, and specify the allowable value.    Then 
  , It will become a Grade enumerated types, you can be shown in the list of three ways to use it: 

  List 3. Use enumerated types 

  Package com.oreilly.tiger.ch03; 

  Public class Student ( 

  Private String firstName; 
  Private String lastName; 
  Private Grade 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 grade) ( 
  This.grade = grade; 
  ) 

  Public Grade getGrade () ( 
  Return grade; 
  ) 
  ) 

  With the previous definition of the type of establishment of a new enumeration (grade), you can use like other members of the same variables 
  Use it.    Of course, the allocation of only enumerated in an enumeration value (for example, A, C or INCOMPLETE).    Moreover, 
  AssignGrade () is no error detection code has not considered the boundary, please note that this is how to do 
  . 

  Use enumerated value 
  So far, what you see examples are very simple, but enumerated type of things much more than these.    You individually 
  Traversing enumeration values in the switch statement can be used in the enumeration values, enumerated is very valuable. 

  Traversing enumerated value 
  Below we have an example showing how to traverse the value of an enumerated type.    4 shows the list of this technology, applied to debugging, 
  Fast printing tasks as well as to set the enumeration loading (I will soon be talking about) tools: 

  List 4. Ergodic enumerated value 

  Public void listGradeValues (PrintStream out) throws IOException ( 
  For (Grade g: Grade.values ()) ( 
  Out.println ( "Allowed value: '" + g + "'"); 
  ) 
  ) 

  Run this code, will be shown in the output list of five: 

  5 list. Iteration operation output 

  Allowed Value: 'A' 
  Allowed Value: 'B' 
  Allowed Value: 'C' 
  Allowed Value: 'D' 
  Allowed Value: 'F' 
  Allowed Value: 'INCOMPLETE' 

  There are many things.    First, I use the Tiger for the new / in circulation (also called foreach or enhanced 
  's For).    In addition, you can see values () method returns a case by an independent Grade consisting of an array 
  Each array has an enumerated type value.    In other words, the values () returns the Grade []. 

  Switching between the enumeration 
  In the enumeration between the value of mobile good, but more important is the basis for decision-making enumeration values.    Of course you can write a pile of 
  If (grade.equals (Grade.A)) types of statements, but that is a waste of time.    Tiger could very easily to pieces 
  Give added support to the good things the past statements on the switch, so it is very easy to use, but also known for your content. 
  6 list 
  Will demonstrate how to solve this problem: 

  List 6. Switch between enumerated 

  Public void testSwitchStatement (PrintStream out) throws IOException ( 
  StringBuffer outputText = new StringBuffer (student1.getFullName ()); 

  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."); 
  Break; 
  ) 

  Out.println (outputText.toString ()); 
  ) 

  Here, enumerated values are transmitted to the switch statement (Remember, getGrade () as an example to return to Grade 
  ), And each case will be dealt with a specific clause value.    The value was not enumerated in the provision of prefixes, which means no 
  Code will be written in case Grade.A only be written in case A could.    If you do not do this, the compiler will not take up 
  By the value of a prefix. 

  Now, you should have been learning how to use a switch statement, the basic syntax, but there are some things you need to know. 
  Prior to the switch in the use of plan 
  As you look forward, in the use of enumeration and switch, you can use the default clause.    This list shows the 7 
  - Usage: 

  List 7. Add a default block 

  Public void testSwitchStatement (PrintStream out) throws IOException ( 
  StringBuffer outputText = new StringBuffer (student1.getFullName ()); 

  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."); 
  Break; 
  Default: 
  OutputText.append ( "has a grade of") 
  . Append (student1.getGrade (). ToString ()); 
  Break; 
  ) 

  Out.println (outputText.toString ()); 
  ) 

  Study the code above we can see that the case has not been any statement dealing with the enumeration of default sentence will be dealt with. 
  You should adhere to the technology used.    The reasons are: Grade assumptions enumerated by your team in other programmers Laws (and 
  He has forgotten to tell you this matter) as shown in the list of 8 version: 

  8 list. Add to the value of an enumeration Grade 

  Package com.oreilly.tiger.ch03; 

  (Public enum Grade 
  A, B, C, D, F, INCOMPLETE, 
  WITHDREW_PASSING, WITHDREW_FAILING 
  ); 

  Now, if the use of the code shown in the list of six new Grade, then these two new values will be ignored.    Worse, 
  You can not even see wrong!    In such circumstances, there can be some common default clause is very important.    - 
  7-not very good to deal with these values, but it will prompt you there are other values, you need to deal with these values.    Upon completion of treatment, 
  You will continue to have a running application procedures, but it will not lose sight of these values, and even guide you next moves 
  .    This is a good coding habits. 

  Enumeration and pool 
  You are familiar with the use of public static final method of encoding those things may have been switched to an enumeration 
  The value of the bond as mapping.    If you do not know the meaning of, please refer to the list nine, it is a wrong message to the public showing 
  Cases of the use of the Ant build file, this may be pop-up information, as follows: 

  List 9. Ant state code 

  Package com.oreilly.tiger.ch03; 

  (Public enum AntStatus 
INITIALIZING,
COMPILING,
COPYING,
JARRING,
ZIPPING,
DONE,
ERROR
  ) 

  Allocation for each state code can understand some people the wrong message, allowing people in the provision of a code Ant View 
  Appropriate error message, this information will be displayed on the console.    This is the map (Map), a perfect use case, and here 
  Each map (Map) is a key enumeration value, and value of each bond is the wrong message.    List of the 10 demonstration 
  Mapping work: 

  List 10. Enumeration of the map (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)); 
  ) 
  ) 

  The use of the generic code (generics) (please refer to reference) and a new structure to establish a new EnumMap mapping. 
  Moreover, the enumeration value through its Class clients, while also providing the type of mapping (in the cases, it 
  Just a simple string).    Methods such as the output of the list of 11 below: 

  Enumerating the Class object 
  You may have already noticed that in the list of 10 that the sample code in Tiger as the enumerated categories, which can be from 
  AntStatus get a Class object that the object is not only available, but they are actually being used.    This is really 
  .    Ultimately, Tiger or the enumeration as a special category type.    Enumerating a concrete realization of the details, please refer to 
  Java 5.0 Tiger: A Developer's Notebook Chapter III (see references). 


  List 11. List of 10 output 

  Running AntStatusTester [echo] … 
  [Java] For status INITIALIZING, the message is: Initializing Ant … 
  [Java] For status COMPILING, the message is: Compiling Java classes … 
  [Java] For status COPYING, the message is: Copying files … 
  [Java] For status JARRING, the message is: JARring up files … 
  [Java] For status ZIPPING, the message is: ZIPping up files … 
  [Java] For status DONE, the message is: Build complete. 
  [Java] For status ERROR, the message is: Error occurred. 

  Further enumeration can be used in conjunction with pool, but much like the new EnumMap structure, Tiger provide a new set of 
  EnumSet realize that allow you to use-operators.    In addition, you can add the enumeration methods, and use them to achieve interface, called specific definition 
  The value of the entity in the entity, a specific code attached to the specific enumeration values.    These features beyond the paper 
  Scope, but in other places, they have detailed files (see references). 

  Enumerating use, but not abuse 
  Learning any new language is crazy use of a dangerous new grammatical structure.    If so, then you would code 
  Suddenly, 80 per cent of generics, tagging and enumeration.    Therefore, you should only use enumerated in the appropriate places to use it.    That 
  Mody, enumerated in the application of what?    A general rule is that any use of the constants, such as the current use switch 
  Constants of code switching.    If there is only a single value (for example, the maximum size of shoes, or can be installed in the cage of monkeys 
  The largest number), or to leave this task bar constants.    However, if the definition of a set of values, and these values in any of 
  1 can be used for specific types of data, it would be enumerated in this place with the most appropriate. 

  </ Td> </ tr> </ table> 

  Function TempSave (ElementID) (CommentsPersistDiv.setAttribute ( "CommentContent" document.getElementById (ElementID). Value); CommentsPersistDiv.save ( "CommentXMLStore");) function Restore (ElementID) (CommentsPersistDiv.load ( "CommentXMLStore"); document . getElementById (ElementID). CommentsPersistDiv.getAttribute value = ( "CommentContent");) </ td> </ tr> <tr> 

  ↑ Back 

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Facebook
  • DotNetKicks
  • DZone
  • Netvouz
  • Propeller

Tags:

Releated Java Articles

Comments

Leave a Reply