Java enumeration Type Usage method detailed _java

Source: Internet
Author: User
Tags stringbuffer

1. Background
before the enumeration type is introduced in the Java language, the common pattern for representing enumerated types is to declare a set of literals that have an int constant. Before we usually use the public final static method to define the code as follows, respectively, 1 for spring, 2 for summer, 3 for autumn, 4 for winter.

public class Season {public
 static final int SPRING = 1;
 public static final int SUMMER = 2;
 public static final int autumn = 3;
 public static final int WINTER = 4;
}

This method is called int enumeration mode. But what is the problem with this model, we have spent so long, should be no problem. Typically, the code we write will consider its security, ease of use, and readability. First, let's consider its type security. Of course this pattern is not type-safe. For example, we design a function that requires the introduction of a certain value of spring and autumn. But using the int type, we cannot guarantee that the value passed in is legitimate. The code looks like this:

Private String Getchineseseason (int season) {
  StringBuffer result = new StringBuffer ();
  Switch (season) {case
   season.spring:
    result.append ("Spring");
    break;
   Case Season.summer:
    result.append ("Summer");
    break;
   Case Season.autumn:
    result.append ("Autumn");
    break;
   Case Season.winter:
    result.append ("Winter");
    break;
   Default:
    result.append ("Seasons without Earth");
    break;
  return result.tostring ();
 }

 public void DoSomething () {
  System.out.println (This.getchineseseason (season.spring));//This is the normal scene

  . System.out.println (This.getchineseseason (5))//This is an abnormal scene, which results in a type-unsafe problem
 }

Program Getchineseseason (season.spring) is the method we expect to use. Can Getchineseseason (5) Obviously is not, and compile very pass, what will happen when run, we are unknown. This obviously does not conform to the type safety of Java programs.

Let's consider the readability of this pattern next. With most of the enumerations, I need to get a string expression for the enumeration type. If the Int enumeration constant is printed, we see a set of numbers, which is of little use. We might think of using a string constant instead of an int constant. Although it provides a printable string for these constants, it can cause performance problems because it relies on the comparison of strings, so this pattern is not what we expect. The disadvantages of int and string enumeration patterns are revealed from both type security and program readability. Fortunately, starting with the Java1.5 release, there is an alternative solution that avoids the drawbacks of the int and string enumeration patterns and offers many additional benefits. That is the enum type. The following sections describe the definition, characteristics, application scenarios, and pros and cons of the enumeration type.

2. Define
An enumeration type (enum type) is a valid type that consists of a set of fixed constants. In Java, an enum type is defined by a keyword enum. The following is the definition of the Java enumeration type.

public enum Season {
 SPRING, SUMMER, Autumn, Winer;
}

3. Features
The statement that Java defines an enumeration type is simple. It has the following characteristics:

1 using the Keyword enum 2) type name, such as the season 3 here, a string of allowable values, such as the Four Seasons, 4, as defined above, the enumeration can be defined individually in one file or in other Java classes.
In addition to such basic requirements, the user has some other options

5) An enumeration can implement one or more interfaces (Interface) 6) can define a new variable 7 and can define a new method 8 to define a class that is different according to a specific enumeration value
4. Application Scenarios
in the case of type safety mentioned in the background, rewrite that piece of code with an enumeration type. The code is as follows:

public enum Season {SPRING (1), SUMMER (2), Autumn (3), WINTER (4);
 private int code;
 Private Season (int code) {This.code = code;
 public int GetCode () {return code; } public class Useseason {/** * Converts the English season to the Chinese season * @param season * @return */public String Getchineseseason
  Son season) {StringBuffer result = new StringBuffer ();
    Switch (season) {case SPRING:result.append ("[Chinese: Spring, enumerated constants:" + season.name () + ", data:" + season.getcode () + "]");
   Break
    Case AUTUMN:result.append ("[Chinese: Autumn, enumerated constants:" + season.name () + ", data:" + season.getcode () + "]");
   Break
    Case SUMMER:result.append ("[Chinese: Summer, enumerated constants:" + season.name () + ", data:" + season.getcode () + "]");
   Break
    Case WINTER:result.append ("[Chinese: Winter, enumerated constants:" + season.name () + ", data:" + season.getcode () + "]");
   Break
    Default:result.append ("Season without Earth" + season.name ());
  Break
 return result.tostring ();
   public void DoSomething () {for (Season s:season.values ()) {System.out.println (Getchineseseason (s));//This is the normal scene}//system.out.println (Getchineseseason (5));
  This is already a compile pass, which ensures that type safety} public static void Main (string[] arg {useseason Useseason = new Useseason ();
 Useseason.dosomething ();

 }
}

[Chinese: Spring, enumerated constants: Spring, Data: 1] [Chinese: Summer, enumerated constants: SUMMER, Data: 2] [Chinese: Autumn, enumerated constants: Autumn, data: 3] [Chinese: Winter, enumerated constants: WINTER, Data: 4]

Here's a question, why do I want to add a field to an enumeration type? The goal is to associate the data with its constants. If 1 represents spring, 2 represents summer.

5. Summary
So when should you use enumerations? Whenever a fixed set of constants is required, such as the number of days of the week, the year, and so on. Or we know the collection of all the values it contains before we compile. The Java 1.5 enumeration meets the needs of the vast majority of programmers, and its simplicity and ease of use feature prominently.

6. Usage
Usage One: Constants

public enum Color { 
 RED, GREEN, BLANK, Yellow 
} 

Usage Two: Switch

Enum Signal { 
 GREEN, yellow, RED 
} public 
class TrafficLight { 
 Signal color = signal.red; 
 public void Change () { 
  switch (color) {case 
  RED: 
   color = signal.green; 
   break; 
  Case YELLOW: 
   color = signal.red; 
   break; 
  Case GREEN: 
   color = signal.yellow; 
   break; 
  }}} 
 

Usage Three: Add a new method to the enumeration

The public enum Color {red 
 ("Red", 1), Green ("green", 2), BLANK ("White", 3), Yello ("Yellow", 4); 
 Member variable 
 private String name; 
 private int index; 
 Construction Method 
 Private Color (String name, int index) { 
  this.name = name; 
  This.index = index; 
 } 
 Normal method public 
 static String getName (int index) {for 
  (Color c:color.values ()) { 
   if (c.getindex () = = Inde x) {return 
    c.name; 
   } 
  } 
  return null; 
 } 
 Get Set method public 
 String GetName () {return 
  name; 
 } 
 public void SetName (String name) { 
  this.name = name; 
 } 
 public int GetIndex () {return 
  index; 
 } 
 public void Setindex (int index) { 
  this.index = index; 
 } 
} 

Usage Four: Methods of overriding enumerations

The public enum Color {red 
 ("Red", 1), Green ("green", 2), BLANK ("White", 3), Yello ("Yellow", 4); 
 Member variable 
 private String name; 
 private int index; 
 Construction Method 
 Private Color (String name, int index) { 
  this.name = name; 
  This.index = index; 
 } 
 Override method 
 @Override public 
 String toString () {return 
  this.index+ "_" +this.name 
 } 
} 

Usage Five: Implement Interface

Public interface Behaviour { 
 void print (); 
 String getInfo (); 
} 
Public enum Color implements behaviour{red 
 ("Red", 1), Green ("green", 2), BLANK ("White", 3), Yello ("Yellow", 4); 
 Member variable 
 private String name; 
 private int index; 
 Construction Method 
 Private Color (String name, int index) { 
  this.name = name; 
  This.index = index; 
 } 
Interface method 
 @Override public 
 String GetInfo () {return 
  this.name; 
 } 
 Interface method 
 @Override public 
 void print () { 
  System.out.println (this.index+ ":" +this.name); 
 } 
 

Usage Six: Organize enumerations using interfaces

Public interface Food { 
 enum Coffee implements food{ 
  Black_coffee,decaf_coffee,latte,cappuccino 
 } 
 enum Dessert implements food{ 
  FRUIT, CAKE, GELATO 
 } 
}

The above is the entire content of this article, I hope to help you learn.

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.