Enumeration in Java (i)

Source: Internet
Author: User

In actual programming, there are often such "datasets", whose values are stable in the program, and the elements in the "dataset" are limited. For example, from Monday to Sunday, seven data elements formed the "data set" of the week, with four data elements forming the "datasets" of the Four seasons. Perhaps the easiest way to think of this dataset in Java is to say, for example, a working day of Five days a week:

public class WeekDay {public static final int MONDAY = 1;        public static final int Tuesday = 2;        public static final int wensday = 3;        public static final int Thursday = 4; public static final int FRIDAY = 5;}

Now, your class can use constants like weekday.tuesday . But there are some problems hidden here, these constants are constants of type int in Java , which means that the method can accept any value of type int , even if it and WeekDay does not correspond to all dates defined in the. Therefore, you need to detect the upper and lower bounds, and you might throw a illegalargumentexceptionwhen an invalid value occurs. Also, if you later add another date (for example, weekday.saturday ), you must change the upper bound in all the code to accept the new value. In other words, this scenario might work, but not very effective, when using classes with integer constants.

Joshua Bloch boss at this time stood out, in his book "Effective Java" put forward in such a scene in a very good mode-Type-safe enumeration pattern . The pattern is simply to give a private constructor to such a constant class, and then declare some of the public static final variables of the same type exposed to the consumer, for example:

Public class weekday {         public static  final weekday monday = new weekday (1);          public static final weekday tuesday = new weekday (2);          public static final weekday wensday  = new weekday (3);          public static  final weekday thursday = new weekday (4);          public static final weekday friday = new weekday (5);                    Public int getvalue () {                    return value;         }                   private int value;                   private  weekday (int i) {                    this.value = i;         }          //other methods ...}

The advantage of this is that your program now accepts data that is not of type int , but rather a predefined static final instance of WeekDay (weekday.tuesday, etc.). ), for example:

public void Setweekday (WeekDay WeekDay) {...}

This also avoids the ability to arbitrarily pass an illegal int type value (for example, 1) to the method, resulting in a program error. It also brings some other benefits: because these enumerated objects are instances of some class, put the required properties in it to hold the data, and because they are all singleton, you can use the equals method or the = = symbol to compare them.

Joshua Bloch greatly proposed enumeration mode, very useful but good trouble ah. If you have used a language such as C + + or Pascal, you will definitely have an impression of their enumeration type, for example, in C + +, we can define

enum weekday {   monday,    Tuesday,   wensday,   thursday,   friday}; 

and then you can use it in the program. MONDAY , Tuesday these variables. This is convenient, but the previous version of Java 1.4 does not provide support for enumeration types, so if you are using JDK 1.4 to develop the program, you can only look like Joshua That's what Bloch boss wrote. starting with Java 5.0(codenamed Tiger), this has changed, andjava Enumeration types are supported from the language level.

Enumeration is a very important new feature of Tiger, which is a new type that allows represented to represent specific pieces of data and is all represented in type-safe form, which is defined using the "enum" keyword.

Let's start by writing a simple enumeration type definition:

Public enum weekday{MONDAY, Tuesday, Wensday, Thursday, FRIDAY;//Last This ";" can write not write. }

This is similar to the definition of class and interface. The enumeration type in Tiger is a class defined using the special syntax "enum". All enum types are subclasses of Java.lang.Enum. This is a newly introduced class in Tiger, which is not itself an enumeration type, but it defines the behavior common to all enum types, such as the following table:

650) this.width=650; "src=" Https://s2.51cto.com/wyfs02/M02/98/70/wKioL1k7-WuwNBaRAAVQao6ogzg479.png "title=" QQ picture 20170610215110.png "alt=" Wkiol1k7-wuwnbaraavqao6ogzg479.png "/>

Note: Although all enum types inherit from Java.lang.Enum, you cannot define enum types by bypassing the keyword "enum" and using the direct inheritance enum. The compiler will prompt an error to prevent you from doing so.

The five enumerated constants defined in weekday are separated using ",". These constants are "public static final" By default, so you don't have to add a "public static final" modifier to them (the compiler will prompt an error), which is why enumeration constants are named in uppercase letters. And each constant is an instance of the enumeration type weekday. You can get the enumeration constants defined in WeekDay by using a format like "Weekday.monday", or you can take a similar "WeekDay oneday = Weekday.monday" To assign a value to an enumeration type variable (you cannot assign an enum-type variable to a value other than an enumeration constant and null, the compiler will prompt an error).

How does an enumeration constant that is an instance of an enumeration type initialize? The answer is simple, and these enumeration constants are initialized by the constructors defined in the enum.

The constructors defined in Java.lang.Enum,//Two parameters are the name of the enumerated constant that is defined, and the order in which it is located.                   Protected Enum (String name, int ordinal) {this.name = name; This.ordinal = ordinal;}

During initialization, the order of enumerated constants is arranged in the order in which they are declared. The order of the first enumerated constant is 0, which accumulates.

Enumeration types In addition to the methods provided by the enum, there are two static methods--values () and valueof (String arg0) that are hidden in relation to the specific enumeration type. The values () method can get an array containing all the enumeration constants, and the method valueof is a simplified version of the method valueof in Java.lang.Enum, which allows you to get the matching enumeration constants in the current enumeration type based on the name passed.


Let's look at a small example of the enumeration type used. Requirements can be specified on the date of the corresponding information output. For such a simple requirement, the enumeration type is used here for processing. We have already defined the enumeration type that contains five business days. The following code is the way to output:

/**         *  output the appropriate date information according to the date's difference.          *  @param  weekDay      Enumeration constants that represent different dates          */          public void printweekday (Weekday weekday) {             switch (WeekDay) {              case MONDAY:                 system.out.println ("today is monday!"); break;             case tuesday:                   System.out.println ("today is tuesday!"); break;             case wensday:                  system.out.println ("today is wensday!"); break;             case thursday:                   System.out.println ("today is hursday!"); break;                    case FRIDAY:                  system.out.println ("today is friday!"); break;                    default:                 throw new assertioNerror ("unexpected value: "  + weekday);                    }          }

Prior to Tiger, the switch operation was only able to operate on int, short, char, and byte. In Tiger, switch adds support for enumeration types because enumeration types only have a finite number of enumerated constants that can be substituted with integers, which is too good for a switch statement! Just like in the code above, you put an enum-type variable in the Swtich expression, you can use the enumeration constants in the enumeration type directly in the case label.

Note: The case notation does not have an enumeration type prefix, which means that the code cannot be written in case operation. Plus, just write it into case plus. Otherwise, the compiler will prompt for an error message.

As in the example above, although you have exhausted all enumerated constants in an enumeration type in the case indicator, it is recommended that you add the default label at the end (as shown in the code above). Because if you add a new enumeration constant to an enumeration type and forget to add the appropriate processing in the switch, it is difficult to find the error.

To better support enumeration types, two new classes have been added to Java.util: Enummap and Enumset. Use them to manipulate enumeration types more efficiently. Let me introduce you to:

Enummap is a map implementation specifically tailored for enumeration types. Although using other map implementations (such as HashMap) can also complete enumeration type instances to be worth mapping, using ENUMMAP is more efficient: it can only receive instances of the same enumeration type as key values, and because the number of enumerated type instances is relatively fixed and limited, So Enummap uses arrays to hold values that correspond to enumerated types. This makes the enummap highly efficient.

Tips: Enummap uses the enumeration type's ordinal () internally to get the declaration order of the current instance, and uses this order to maintain the position of the corresponding value of the enumeration type instance in the array.

    The following is a code example that uses Enummap. The enumeration type DatabaseType contains all the database types currently supported. For different databases, some database-related methods need to return values that are not the same, as in the example Geturl.

The currently supported database type enumeration type definition public enum databasetype{                    mysql,oracle,db2,sqlserver} // A method for obtaining a database URL as defined in a class and a declaration of Enummap. ......private enummap<databasetype ,string> urls =new enummap<databasetype  ,string> (Databasetype.class);                    public databaseinfo () {          urls.put (DATABASETYPE.DB2, "Jdbc:db2://localhost:5000/sample");          urls.put (Databasetype.mysql, "Jdbc:mysql://localhost/mydb");          urls.put (Databasetype.oracle, "Jdbc:oracle:thin: @localhost: 1521:sample");          urls.put (Databasetype.sqlserver, "jdbc:microsoft:sqlserver:// Localhost:1433;daTabasename=mydb ");}  /***  returns a new instance of the corresponding url*  @param  type     databasetype enumeration class based on the different database types *   @return */public string geturl (databasetype type) {          return this.urls.get (type);}

In practical use, Enummap object URLs are often populated with code that is externally responsible for the entire application initialization. For the convenience of demonstration, the class has done its own content filling.

As in the example, it is convenient to use Enummap to bind to different values in different environments for enumerated types. For example, Geturl is bound to a URL and may be bound to a database driver in other code.

Enumset is a high-performance set implementation of enum types. It requires that the enumeration constants put into it must belong to the same enumeration type. Enumset provides a number of factory methods to facilitate initialization, as shown in the following table:

650) this.width=650; "src=" Https://s5.51cto.com/wyfs02/M01/98/70/wKioL1k7-hGxaknTAAMyuAQOHX8706.png "title=" QQ picture 20170610215411.png "alt=" Wkiol1k7-hgxakntaamyuaqohx8706.png "/>

Enumset is implemented as a set interface that supports traversal of included enumeration constants:

For (Operation Op:EnumSet.range (Operation.plus, operation.multiply)) {

DoSomething (OP);

}

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.


Reprint to: http://blog.csdn.net/shimiso/article/details/5909217

This article is from the "Ciyo Technology sharing" blog, please be sure to keep this source http://ciyorecord.blog.51cto.com/6010867/1934198

Enumeration in Java (i)

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.