Enum,enummap,enumset

Source: Internet
Author: User
Tags dateformat

Enum Basic use


Package com.enumtest;

Enum Shrubbery {
GROUND, crawling, hanging}

public class Enumclass {
public static void Main (string[] args) {
For (shrubbery s:shrubbery.values ()) {
SYSTEM.OUT.PRINTLN (S + "ordinal:" + s.ordinal ());
System.out.println (S.compareto (shrubbery.crawling) + "");
System.out.println (S.equals (shrubbery.crawling) + "");
System.out.println (s = = shrubbery.crawling);
System.out.println ("S.getdeclaringclass:" + s.getdeclaringclass ()
+ "GetClass:" + s.getclass ());
System.out.println (S.name ());
System.out.println ("——————————-");
}
String[] arraystring= "Hanging crawling GROUND". Split ("");
for (String s:arraystring) {
Shrubbery shrub = enum.valueof (Shrubbery.class, s);
System.out.println (shrub);
}
}
}

    1. Each enum instance (GROUND, crawling, hanging) records a sequence original (0,1,2).
      2. Implement the comparable interface, rewrite the CompareTo to compare order by original, and only run the same enum type instance for comparison.
      3.equals Comparing memory addresses
      4. The serializable interface is implemented.

In addition to a few limitations, we can treat an enum as a normal type:
Package com.enumtest;

public enum Ozwitch {

//you must define enum instances firstly.WEST("west"), NORTH("north"), EAST("east"), SOUTH("south");private String description;//even if the constructor is public .. , it‘s nonsense!private OzWitch(String description) {    this.description = description;}public String getDescription() {    return description;}public static void main(String[] args) {    for (OzWitch witch : OzWitch.values()) {        System.out.println(witch + ":" + witch.getDescription());    }}

}

The enum type can be used in a switch statement

. switch (integer or enum) {
Case ....
}
Enum Signal {
GREEN, YELLOW, RED
}

public class TrafficLight {
Signal color = signal.red;

public void change() {    switch (color/*枚举实例*/) {    //case ** 被强制用color类型的实例    case RED:        color = Signal.GREEN;        break;    case GREEN:        color = Signal.YELLOW;        break;    case YELLOW:        color = Signal.RED;        break;    }}public String toString() {    return "The traffic light is " + color;}public static void main(String[] args) {    TrafficLight t = new TrafficLight();    for (int i = 0; i < 7; i++) {        System.out.println(t);        t.change();    }}

}

The difference between the keyword enum and the java.lang.Enum:
Let's look at the following code:

Enum Explore {here, there}

public class Reflection {
public static Set analyze (Class

Package com.enumtest;
Enumeration in the enumeration
public enum Course {
Defining three enumeration instances
Appetizer (Food.Appetizer.class),
Maincourse (Food.MainCourse.class),
COFFEE (Food.Coffee.class);
A domain is used to get the instances contained in each instance
Private food[] Allfood;

//构造器获得一个枚举类型中的所有实例  //这个构造器 ,通过入参获取该入参对应的所有实例Course(Class<? extends Food> clazz) {    allFood = clazz.getEnumConstants();}//随机获取一个枚举(如 APPETIZER)中的枚举实例(如 SALAD,SOUP,RED_WINE)中的一个public Food randomSelection() {    return Enums.random(allFood);}

public static void Main (string[] args) {
for (int i = 0; i < course.values (). length; i++) {
For (Course course:Course.values ()) {
Food food = course.randomselection ();
SYSTEM.OUT.PRINTLN (food);
}
System.out.println ("——— –");
}
In addition, there is a simple way to organize (choose a kind of, personal inclination the first kind, clear! ):

 Public enumMeal2 {appetizer (Food.Appetizer.class), Maincourse (Food.MainCourse.class), Dessert (Food.Dessert.class), COFFEE ( Food.Coffee.class);PrivateFood[] values;Private Meal2(CLASS&LT; extends food> kind) {736ThinkinginchJava Bruce eckelvalues = Kind.getenumconstants ();} Public InterfaceFood {enumAppetizer implements food {salad, SOUP, spring_rolls;}enumMaincourse implements food {lasagne, BURRITO, Pad_thai,lentils, hummous, Vindaloo;}enumDessert implements Food {tiramisu, GELATO, Black_forest_cake,fruit, Creme_caramel;}enumCoffee implements food {black_coffee, Decaf_coffee, Espresso,latte, Cappuccino, TEA, Herb_tea;}} PublicFoodrandomselection() {returnEnums.random (values);} Public Static void Main(string[] args) { for(inti =0; I <5; i++) { for(Meal2 meal:Meal2.values ()) {Food food = meal.randomselection (); System. out. println (food);} System. out. println ("---");}}}/ * Same output as Meal.java * ///:~
Enumset

1. Its operation is faster than HashSet, long-based storage
The elements in 2.EnumSet must be enum types, and the order of the elements after initialization is consistent with the order of enum instance definitions

Import Java. Util. Enumset;public class Enumsets {public static void main (string[] args) {enumset<alarmpoints> points = Enumset. noneof(alarmpoints. Class);Points. Add(alarmpoints. Bathroom);System. out. println(points);Points. AddAll(Enumset. of(alarmpoints. STAIR1, Alarmpoints. STAIR2, Alarmpoints. KITCHEN));System. out. println(points);Points = Enumset. AllOf(alarmpoints. Class);Points. RemoveAll(Enumset. of(alarmpoints. STAIR1,alarmpoints. STAIR2,alarmpoints. KITCHEN));System. out. println(points);The parameter Rangefrom,rangeto all contain points. RemoveAll(Enumset. Range(alarmpoints. STAIR1, Alarmpoints. STAIR2));System. out. println(points);Ask for a difference set points = Enumset. Complementof(points);System. out. println(points);}}

Enumset is based on a long (64bit) construct, through enumset result = noneof (ElementType), initialization, and the element in Enumset with a bit to indicate its existence. Therefore, if the number of enum elements initialized more than 64 will increase the number of long, if less than 64, there will be only a long memory space.
(e.g. source code: elements used to save elements)
/**
* Bit vector representation of this set. The 2^k bit indicates the
* Presence of universe[k] in this set.
*/
Private long elements = 0L;

Enummap

1.key must be an instance of an enum that specifies (the constructor's initial), which is implemented internally by an array and is fast
2. The sequence of elements after initialization is consistent with the order of enum instance definitions, and other operations are similar to map
3. Achieving multi-channel distribution (multiple dispatching)

//Command mode 1. There is usually an interface that has only one single methodInterfaceCommand {voidAction ();} Public classEnummaps { Public Static void Main(string[] args) {enummap<alarmpoints, command> em =NewEnummap<alarmpoints, command> (Alarmpoints.class);The //em key is only allowed to be an instance of the Alarmpoints.class defined by the initializationEm.put (Alarmpoints.kitchen,NewCommand () {//Command mode 2. Implement sub-implementations with different behaviors from this interface@Override Public void Action() {System. out. println ("Kitchen fire!");        }        }); Em.put (Alarmpoints.bathroom,NewCommand () {@Override Public void Action() {System. out. println ("Bathroom fire!"); }        }); for(map.entry<alarmpoints,command> E:em.entryset ()) {System. out. println ("E.getkey ()"+e.getkey ());        E.getvalue (). Action (); }Try{em.Get(alarmpoints.utility). Action (); }Catch(Exception e)        {e. Printstacktrace (); }     }}
Constant specified method (Constantspecific methods)
 Public enumConstantspecificmethod {date_time {String getInfo () {returnDateformat.getdateinstance (). Format (NewDate ()); }}, CLASSPATH {String getInfo () {returnSystem.getenv ("CLASSPATH"); }}, VERSION {String getInfo () {returnSystem.getproperty ("Java.version"); }    };//Declare an abstract method (or common method-the default behavior method, and then say)    AbstractString GetInfo (); Public Static void Main(string[] args) { for(Constantspecificmethod constantspecmethod:values ()) {System. out. println ("\\s"+constantspecmethod.getinfo ()); }    }}

This is also known as the table-driven code (see < Codes complete>). Similar to the command pattern, except for the generic interface of the command pattern, which is replaced by the enum class.
OOP has different classes associated with different behaviors, and with constant methods, each instance is a separate type (of course, it is not the same as "class"). An enum class in the example above appears to be treated as a "superclass", in which each instance behaves differently through GetInfo (), polymorphic.

Enum Likeclasses {winken {voidBehavior () {print ("Behavior1"); }},blinken {voidBehavior () {print ("Behavior2"); }},nod {voidBehavior () {print ("Behavior3"); } };Abstract voidBehavior ();} Public classnotclasses {//Void F1 (Likeclasses.winken instance) {}//Nope}/* Output: Post-compilation code compiled from"Notclasses.java"Abstract classLikeclasses extends java.lang.enum{ Public StaticFinal likeclasses Winken; Public StaticFinal likeclasses Blinken; Public StaticFinal Likeclasses nod;...*///

1.abstract class Likeclasses extends java.lang.Enum an abstract class
2. The method constant is the static domain (field) of this abstract class

* * The abstract method can also be used for common methods, then the default is given to each enum instance a default method:

 Public enumConstantspecificmethod {date_time,//give default GetInfo ()    / * * {String getInfo () {return dateformat.getdateinstance (). Format (NEW * Date ());}}, * /CLASSPATH {String GetInfo () {returnSystem.getenv ("CLASSPATH"); }}, VERSION {String getInfo () {returnSystem.getproperty ("Java.version");    }    }; String GetInfo () {System. out. println ("Default");return NULL; }; Public Static void Main(string[] args) { for(Constantspecificmethod constantspecmethod:values ()) {System. out. println (Constantspecmethod.getinfo ()); }    }}

Enum,enummap,enumset

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.