In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)06/01 Report--
In practical programming, there are often such "datasets" whose values are stable in the program, and the elements in the "dataset" are limited. For example, seven data elements from Monday to Sunday make up the "data set" of the week, and four data elements of spring, summer, autumn and winter form the "data set" of the four seasons. The easiest way to represent such a dataset in Java is probably like this. Let's take a five-day working week as an example:
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 hidden problems. These constants are constants of type int in Java, which means that the method can accept any value of type int, even if it does not correspond to all the dates defined in WeekDay. Therefore, you need to check the upper and lower bounds, and perhaps throw an IllegalArgumentException when an invalid value occurs. Also, if you add another date later (for example, WeekDay.SATURDAY), you must change the upper bound in all your code to accept the new value. In other words, this solution may be feasible when using such classes with integer constants, but it is not very effective.
Boss Joshua Bloch came forward at this time and proposed a very good model in such a scenario-Type-safe enumeration pattern in his book Effective Java. In short, the pattern is to give such a constant class a private constructor, and then declare some variables of the same type of public static final to expose to the user, such as:
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 instead of accepting data of type int, your program now accepts a predefined instance of static final of WeekDay (WeekDay.TUESDAY, etc.), such as:
Public void setWeekDay (WeekDay weekDay) {...}
This also avoids program errors caused by arbitrarily passing an illegal int value (for example,-1) to the method. At the same time, it also brings some other benefits: because the objects of these enumerations are instances of some classes, put some required properties to store the data; and because they are all singletons, you can use the equals method or the = = symbol to compare them.
Joshua Bloch greatly proposed the enumeration mode, which is easy to use but troublesome. If you have used languages such as CCompact + or Pascal, you must be impressed by their enumerated types, for example, we can define them like this in Calgary +.
Enum weekday {MONDAY, TUESDAY, WENSDAY, THURSDAY, FRIDAY}
Then the variables MONDAY and TUESDAY can be used in the program. This is convenient, but previous versions of Java 1.4 did not provide support for enumerated types, so if you are developing programs in JDK 1.4, you can only write like the boss of Joshua Bloch. This has changed since java 5. 0 (codenamed Tiger), and Java supports enumerated types at the language level.
Enumeration is a very important new feature of Tiger. It is a new type that allows specific pieces of data to be represented by constants, all in a type-safe form, and defined using the "enum" keyword.
Let's start with a simple definition of enumerated types:
Public enum WeekDay {MONDAY, TUESDAY, WENSDAY, THURSDAY, FRIDAY; / / the last ";" can be written or not. }
This is very similar to the definition of class and interface. An enumerated type in Tiger is a class defined using the special syntax "enum". All enumerated types are subclasses of java.lang.Enum. This is a new class introduced in Tiger. It is not an enumerated type itself, but it defines the behavior common to all enumerated types, as shown in the following table:
Note: although all enumerated types inherit from java.lang.Enum, you cannot define enumerated types by directly inheriting Enum, bypassing the keyword "enum". The compiler will prompt an error to prevent you from doing so.
The five enumeration constants defined in WeekDay are separated by ",". These constants are "public static final" by default, so you don't have to public static final them (the compiler prompts an error), which is why enumeration constants are named in uppercase letters. And each constant is an instance of the enumerated type WeekDay. You can get the enumeration constants defined in WeekDay through a format like "WeekDay.MONDAY", or you can assign values to enumerated type variables in a similar way as "WeekDay oneDay = WeekDay.MONDAY" (you can't assign values to enumerated type variables other than enumeration constants and null, the compiler will prompt for an error).
How are enumeration constants initialized as instances of enumerated types? The answer is simple: these enumeration constants are initialized through the constructors defined in Enum.
The constructor defined in / / java.lang.Enum, / / the two arguments are the name of the defined enumeration constant 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 enumeration constants is arranged in the order of declaration. The order of the first enumeration constant is 0, which accumulates accordingly.
In addition to having methods provided by Enum, enumerated types have two hidden static methods related to specific enumerated types-values () and valueOf (String arg0). Method values () can get an array containing all enumeration constants; method valueOf is a simplified version of method valueOf in java.lang.Enum, through which you can get matching enumeration constants in the current enumeration type based on the name passed.
Let's look at a small example of the use of enumerated types. The requirement requires that the corresponding information output can be carried out on the specified date. For such a simple requirement, enumerated types are used here. Previously, we have defined an enumeration type that contains five working days. The following code is the way to output:
/ * * output the corresponding date information according to the date. * @ param weekDay represents enumeration constants for 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, switch operations could only operate on int, short, char, and byte. In Tiger, switch adds support for enumerated types, because enumerated types contain only a limited number of enumerated constants that can be replaced by integers, which is perfect for using switch statements! As in the above code, you can use enumerated constants directly in the case tag by placing enumerated type variables in the swtich expression.
Note: there is no enumerated type prefix in the case notation, which means that the code cannot be written as case Operation. PLUS, just write it as case PLUS. Otherwise, the compiler prompts for an error message.
Like the example above, although you have exhausted all the enumeration constants in an enumerated type in the case tag, it is recommended that you add the default tag at the end (as indicated by the code above). Because if you add a new enumeration constant to an enumerated type and forget to add the corresponding processing in switch, it's hard to find an error.
To better support enumerated types, two new classes have been added to java.util: EnumMap and EnumSet. Use them to manipulate enumerated types more efficiently. Let me introduce you one by one:
EnumMap is a Map implementation tailored to enumerated types. Although it is possible to map enumerated type instances to values using other Map implementations such as HashMap, using EnumMap is more efficient: it can only accept instances of the same enumerated type as key values, and because the number of enumerated type instances is relatively fixed and limited, EnumMap uses arrays to hold values corresponding to enumerated types. This makes EnumMap very efficient.
Tip: EnumMap internally uses the ordinal () of the enumerated type to get the declaration order of the current instance and uses this order to maintain the location of the corresponding values of the enumerated type instance in the array.
The following is a code example that uses EnumMap. The enumerated type DataBaseType holds all the database types that are now supported. Some database-related methods need to return different values for different databases, such as getURL in the example.
/ / currently supported database type enumeration type definition public enum DataBaseType {MySQL,Oracle,DB2,SQLSERVER} / / the method of getting database URL defined in a class and the declaration of EnumMap. Private EnumMap urls = new EnumMap (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 ");} / * return the corresponding new instance of URL* @ param type DataBaseType enumerated class * @ return*/public String getURL (DataBaseType type) {return this.urls.get (type);} according to different database types.
In practical use, the EnumMap object urls is often populated by external code responsible for initializing the whole application. Here, for the convenience of demonstration, the class has done its own content filling.
As in the example, using EnumMap makes it easy to bind enumerated types to different values in different environments. For example, getURL is bound to URL in the example, and may be bound to the database driver in other code.
EnumSet is a high-performance Set implementation of enumerated types. It requires that the enumeration constants placed into it must be of the same enumeration type. EnumSet provides many factory methods to facilitate initialization, as shown in the following table:
EnumSet, implemented as a Set interface, 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 enumerated collections. EnumSet guarantees that the elements in the collection are not duplicated; key in EnumMap is of type enum, while value can be of any type.
Reproduced to: http://blog.csdn.net/shimiso/article/details/5909217
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.