"Go" Mastering the Java Enumeration type (enum type)

Source: Internet
Author: User

Original URL: http://iaiai.iteye.com/blog/1843553

1 background

Before an enumeration type is introduced in the Java language, a common pattern that represents an enumeration type is to declare a set with an int constant. Before we usually use the public final static method to define the code as follows, with 1 for the spring, 2 for summer, 3 for autumn, 4 for winter.

Java code
  1. Public class Season {
  2. public static final int SPRING = 1;
  3. public static final int SUMMER = 2;
  4. public static final int AUTUMN = 3;
  5. public static final int WINTER = 4;
  6. }


This method is called an int enumeration pattern. But what's wrong with this model, we've been using it for so long, it should be okay. Often the code we write will consider its security, ease of use, and readability.

First, let's consider its type safety. Of course, this pattern is not type-safe. Let's say we design a function that asks for a value to pass through the spring and autumn. However, with the int type, we cannot guarantee that the value passed in is legal. The code looks like this:

Java code
  1. Public class Season {
  2. public static final int SPRING = 1;
  3. public static final int SUMMER = 2;
  4. public static final int AUTUMN = 3;
  5. public static final int WINTER = 4;
  6. private String Getchineseseason (int season) {
  7. StringBuffer result = new StringBuffer ();
  8. switch (season) {
  9. Case season.spring:
  10. Result.append ("Spring");
  11. Break ;
  12. Case Season.summer:
  13. Result.append ("Summer");
  14. Break ;
  15. Case Season.autumn:
  16. Result.append ("Autumn");
  17. Break ;
  18. Case Season.winter:
  19. Result.append ("Winter");
  20. Break ;
  21. Default:
  22. Result.append ("The earth does not have the season");
  23. Break ;
  24. }
  25. return result.tostring ();
  26. }
  27. public void DoSomething () {
  28. System.out.println (This.getchineseseason (season.spring)); This is a normal scene.
  29. System.out.println (This.getchineseseason (5)); This is not a normal scenario, which leads to type insecurity .
  30. }
  31. public static void Main (string[] arg) {
  32. Season Season = new Season ();
  33. Season.dosomething ();
  34. }
  35. }


Program Getchineseseason (season.spring) is the method we expect to use. The Getchineseseason (5) is obviously not, and the compilation is passed, and what happens at runtime is unknown to us. This obviously does not conform to the type safety of Java programs.

Next, let's consider the readability of this pattern. In most cases where enumerations are used, I need to be convenient to get string expressions of enumerated types. If you print an int enumeration constant, what we see is a set of numbers, which is of little use. We might think of using string constants instead of int constants. Although it provides a printable string for these constants, it can cause performance problems because it relies on string comparison operations, so this pattern is something we don't expect.

In terms of type safety and program readability, the disadvantages of the int and string enumeration patterns are revealed. Fortunately, starting with the Java1.5 release, there is another alternative solution that avoids the drawbacks of the int and string enumeration patterns and provides many additional benefits. That is the enumeration type (enum type). The following chapters describe the definitions, characteristics, scenarios, and pros and cons of enumeration types.

2 Definitions

An enumerated type (enum type) refers to a fixed set of constants that make up a valid type. In Java, the keyword enum defines an enumeration type. The following is the definition of the Java enumeration type.

Java code
    1. Public enum Season {
    2. SPRING, SUMMER, AUTUMN, WINTER;
    3. }



3 Features

The statements for Java-defined enumeration types are simple. It has the following characteristics:
1) using the keyword enum
2) Type names, such as the season here
3) A list of allowable values, such as the Four Seasons defined above
4) Enumerations can be individually defined in one file or embedded in other Java classes
In addition to this basic requirement, the user has some other options
5) enumeration can implement one or more interfaces (Interface)
6) You can define a new variable
7) You can define a new method
8) You can define classes that differ based on specific enumeration values
4 Application Scenarios

As an example of type safety mentioned in the background, rewrite that code with an enumeration type. The code is as follows:

Java code
  1. Public enum Season {
  2. SPRING (1), SUMMER (2), AUTUMN (3), WINTER (4);
  3. private int code;
  4. private Season (int code) {
  5. This.code = code;
  6. }
  7. public int GetCode () {
  8. return code;
  9. }
  10. }

Java code
  1. Public class Useseason {
  2. /**  
  3. * Convert the English season to the Chinese season
  4. * @param season
  5. * @return
  6. */
  7. Public String Getchineseseason (Season Season) {
  8. StringBuffer result = new StringBuffer ();
  9. switch (season) {
  10. Case SPRING:
  11. Result.append ("[Chinese: Spring, Enumeration constant:" + season.name () + ", data:" + season.getcode () + "]");
  12. Break ;
  13. Case AUTUMN:
  14. Result.append ("[English: Autumn, Enumeration constants:" + season.name () + ", data:" + season.getcode () + "]");
  15. Break ;
  16. Case SUMMER:
  17. Result.append ("[English: Summer, Enumeration constant:" + season.name () + ", data:" + season.getcode () + "]");
  18. Break ;
  19. Case WINTER:
  20. Result.append ("[English: Winter, Enumeration constant:" + season.name () + ", data:" + season.getcode () + "]");
  21. Break ;
  22. Default:
  23. Result.append ("The earth does not have the season" + Season.name ());
  24. Break ;
  25. }
  26. return result.tostring ();
  27. }
  28. public void DoSomething () {
  29. For (Season s:season.values ()) {
  30. System.out.println (Getchineseseason (s)); //This is the normal scene
  31. }
  32. //system.out.println (Getchineseseason (5));
  33. //The compilation is not passed here, which guarantees type safety
  34. }
  35. public static void Main (string[] arg) {
  36. Useseason Useseason = new Useseason ();
  37. Useseason.dosomething ();
  38. }
  39. }

References [Chinese: Spring, Enumeration constants: Spring, Data: 1]
[English: Summer, Enumeration constants: SUMMER, Data: 2]
[English: Autumn, Enumeration constants: AUTUMN, Data: 3]
[English: Winter, Enumeration constants: WINTER, Data: 4]



Here's a question, why do I add a domain to an enumeration type? The goal is to associate the data with its constants. As 1 stands for Spring, 2 for summer.

5 Summary

So when should I use enumerations? Whenever you need a fixed set of constants, such as days of the week, year-round, etc. Or we know the collection of all the values it contains before we compile. The advantage is: enumeration can meet the requirements of most programmers, its concise, easy-to-use features are very prominent. Cons: Enumerations have a small performance disadvantage when compared to int constants, where there is a cost of space and time to load and initialize enumerations. such as resource-constrained devices: mobile phones and so on.

"Go" Mastering the Java Enumeration type (enum type)

Related Article

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.