Java Enumeration Common operations

Source: Internet
Author: User

Before JDK1.5, we defined constants: public static fianl ..... Now, with enumerations, you can group related constants into an enumeration type, and enumerations provide more methods than constants.

Java code
    1. Public enum Color {
    2. }

The switch statement before JDK1.6 only supports int,char,enum types, and using enumerations can make our code more readable.

Java code
    1. Enum Signal {
    2. }
    3. Public class TrafficLight {
    4. public Void Change () {
    5. switch (color) {
    6. Case RED:
    7. Break ;
    8. Case YELLOW:
    9. Break ;
    10. Case GREEN:
    11. Break ;
    12. }
    13. }

If you intend to customize your own method, you must add a semicolon at the end of the enum instance sequence. And Java requires that an enum instance be defined first.

Java code
  1. Public enum Color {
  2. "Red", 1), Green ("green", 2), BLANK ("White", 3), Yello ("Yellow", 4);
  3. Member variables
  4. private String name;
  5. private int index;
  6. Construction method
  7. Private Color (String name, int index) {
  8. THIS.name = name;
  9. This.index = index;
  10. //Common method
  11. Public static String getName (int index) {
  12. For (Color c:color.values ()) {
  13. if (c.getindex () = = index) {
  14. return c.name;
  15. }
  16. return null;
  17. //Get Set Method
  18. Public String GetName () {
  19. return name;
  20. public void SetName (String name) {
  21. THIS.name = name;
  22. public int GetIndex () {
  23. return index;
  24. public void Setindex (int index) {
  25. This.index = index;
  26. }

An example of the ToString () method overlay is given below.

Java code
  1. Public enum Color {
  2. "Red", 1), Green ("green", 2), BLANK ("White", 3), Yello ("Yellow", 4);
  3. Member variables
  4. private String name;
  5. private int index;
  6. Construction method
  7. Private Color (String name, int index) {
  8. THIS.name = name;
  9. This.index = index;
  10. //Coverage Method
  11. @Override
  12. Public String toString () {
  13. return this.index+"_" +this.name;
  14. }

All enumerations are inherited from the Java.lang.Enum class. Because Java does not support multiple inheritance, enumeration objects can no longer inherit from other classes.

Java code
  1. Public interface Behaviour {
  2. void print ();
  3. }
  4. Public enum Color implements behaviour{
  5. "Red", 1), Green ("green", 2), BLANK ("White", 3), Yello ("Yellow", 4);
  6. Member variables
  7. private String name;
  8. private int index;
  9. Construction method
  10. Private Color (String name, int index) {
  11. THIS.name = name;
  12. This.index = index;
  13. Interface method
  14. @Override
  15. Public String GetInfo () {
  16. return this.name;
  17. //interface method
  18. @Override
  19. Public void Print () {
  20. this.index+":" +this.name);
  21. }

Java Code

    • Public interface Food {
    • Enum Coffee implements food{
    • }
    • Enum Dessert implements food{
    • }
    • }

Java.util.EnumSet and Java.util.EnumMap are two enumeration collections. Enumset guarantees that the elements in the collection are not duplicated; The key in Enummap is the enum type, and value can be any type. The use of this two collection is not mentioned here, you can refer to the JDK documentation.

For the implementation details and principles of enumerations, please refer to:

Reference: "Thinkinginjava" fourth edition

http://softbeta.iteye.com/blog/1185573

My article, because it is reproduced, may be basically no change, resulting in someone stepping on a foot. I don't think it fits my big bro character. Below I understand the use of oneself to tidy up a bit.

Because it was just beginning to learn. The usual self-understanding of things are only about to understand a bit, in the final analysis, or self-thought to understand, in fact, in the blink of an eye do not know what is.
Come out to study, not accustomed to see the code how can do?
Here is my own test code.


[Java]View PlainCopy
  1. Package com.lxk.enumTest;
  2. /**
  3. * Java Enumeration Usage test
  4. * <p>
  5. * Created by Lxk on 2016/12/15
  6. */
  7. Public class Enumtest {
  8. public static void Main (string[] args) {
  9. Forenum ();
  10. Useenuminjava ();
  11. }
  12. /** 
  13. * Loop enumeration, output ordinal property, or output if the enumeration has internal properties. (I'm talking about the TypeName property of the enumeration of type types I've defined)
  14. */
  15. private static void Forenum () {
  16. For (Simpleenum simpleEnum:SimpleEnum.values ()) {
  17. System.out.println (Simpleenum + "ordinal" + simpleenum.ordinal ());
  18. }
  19. System.out.println ("------------------");
  20. For (TYPE type:TYPE.values ()) {
  21. System.out.println ("type =" + Type + "Type.Name =" + type.name () + "TypeName =" + Type.gettypename ()  + "ordinal =" + type.ordinal ());
  22. }
  23. }
  24. /** 
  25. * Use enumerations in Java code
  26. */
  27. private static void Useenuminjava () {
  28. String typeName = "F5";
  29. Type type = Type.fromtypename (typeName);
  30. if (TYPE. Balance.equals (type)) {
  31. System.out.println ("Instances of enumerated types obtained from strings are consistent with enumeration constants");
  32. } Else {
  33. System.out.println ("Big bro Code Error");
  34. }
  35. }
  36. /** 
  37. * Season enumeration (enumeration constants without parameters) This is the simplest example of enumerating usages
  38. * The Ordinal attribute, which corresponds to the order of arrangement, starts from 0.
  39. */
  40. private enum Simpleenum {
  41. SPRING,
  42. SUMMER,
  43. AUTUMN,
  44. WINTER
  45. }
  46. /** 
  47. * Common types (enumeration constants with parameters, this is only in the book is not common, the actual use of a lot of, to understand this, use is not a problem.) )
  48. */
  49. private enum TYPE {
  50. FIREWALL ("FIREWALL"),
  51. SECRET ("Secretmac"),
  52. BALANCE ("F5");
  53. private String TypeName;
  54. TYPE (String typeName) {
  55. this.typename = typeName;
  56. }
  57. /** 
  58. * Returns an enumeration instance of the type, based on the name of the type.
  59. *
  60. * @param typeName type name
  61. */
  62. public static TYPE fromtypename (String typeName) {
  63. For (TYPE type:TYPE.values ()) {
  64. if (Type.gettypename (). Equals (TypeName)) {
  65. return type;
  66. }
  67. }
  68. return null;
  69. }
  70. Public String Gettypename () {
  71. return This.typename;
  72. }
  73. }
  74. }


Then the result diagram of the test:



Simple example, we have basically used, can not understand the basic is the second example. As you can see, in the second example, with parameters, you can actually understand this.

The keyword enum is understood to be similar to class, and this is a separate class. As you can see, there are properties in the above example, there are construction methods, there are getter, can also have setter, but the general is the construction of parameters. There are additional custom methods. So in front of these things, separated by commas, and finally with a semicolon, this part is called the instance of this enumeration. It can also be understood as the instance object of class new. This is a good understanding. Just, Class,new object, can own casually new, think a few on a few, and this enum keyword, he does not, his instance object, can only be embodied in this enum. In other words, his corresponding instance is limited. This is the benefit of enumeration, limiting the scope of certain things, for a chestnut: all year round, there can only be four seasons, if you are a string representation, then the sea went, but, to use the enumeration type, you put all the options in the parentheses of the enum, all the columns out, then this season's properties, corresponding values, It can only be picked up inside. There's no other.

My example above is that according to TypeName, you can pick from those examples the only type of enumeration instance--type.balance. Note Method

Type type = Type.fromtypename (typeName);
The return type of this method is the type enumerated.
This is a good idea, how does this enumeration work?

Add:

There are actually three attributes in the instance of the enumerated type with the parameter above, and in addition to my custom TypeName, 2 are the system's own. Look at the following source map:



After seeing this, I don't know if you can understand the following picture: The following image mainly describes the specifications and standards when using enumerations. I hope we can use it in the actual development time.



Finally, add one point:

Maybe you know, but maybe you don't know? I really do not know, after the test did not know!!!

The comparison of values between enumerated type objects is that you can use = = to compare values directly, whether they are equal, not the one that must use the Equals method.

Java Enumeration Common operations

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.