Java core --- Enumeration

Source: Internet
Author: User

Java core --- Enumeration
I. Create a final-state Season class using enumeration in the form of common classes and set the constructor method to private, because the enumeration value cannot be added at will because the class object cannot be new, therefore, you need to define the member variables and write new in the class so that you can access the enumerated values outside the class by using the static member variables of the category class, the method can only be used outside the class and in the enumeration value class Season defined internally in the enumeration class. We set the Earth to public and the return value of the 1/4 method is Season, all the enumerated values in the corresponding class will rotate the 1/4 rewrite method toString (), print the enumerated value, and test it. Print the next value of an enumerated value, output/Enumeration/src/yuki/core/enumeration/imitation/SeasonTest after toString. java copy code package yuki. core. enumeration. imitation; public class SeasonT Est {public static void main (String [] args) {Season season = Season. AUTUMN; System. out. println (season. nextQuarter ();} copy the code/Enumeration/src/yuki/core/enumeration/imitation/Season. java copy code package yuki. core. enumeration. test; public final class Season {// private constructor private Season () {}// defines the static member constant public final static Season SPRING = new Season (); public final static Season SUMMER = new Season (); public Final static Season AUTUMN = new Season (); public final static Season WINTER = new Season (); // defines that the Earth has switched to 1/4 public Season nextQuarter () {Season ret = null; if (this = WINTER) ret = SPRING; else if (this = SPRING) ret = SUMMER; else if (this = SUMMER) ret = AUTUMN; else if (this = AUTUMN) ret = WINTER; return ret;} // print the enumerated value @ Override public String toString () {return this = WINTER? "Winter": (this = SPRING? "Spring": (this = SUMMER? "Summer": "Autumn") ;}} you can see that a large number of if-else, it seems that it is not good to write the nextQuarter of each element into its own independent method. This requires the definition of an abstract nextQuarter so that to create an object, you must first implement the class that has the abstract method. in this case, the method of directly using new to create an object will be red. Using its subclass to create an instance object is defined as an abstract class and a subclass is required to implement its abstract method, this is to remove the final modifier and implement the abstract method nextQuarter () in each enumeration worthy class. test again here, convert unified if-else statements into independent classes/Enumeration/src/yuki/core/enumeration/imitation/Season. java copy code package yuki. core. enumeration. imitation; public abstract class S Eason {// private constructor private Season () {}// defines the static member constant public final static Season SPRING = new Season () {@ Override public Season nextQuarter () {return SUMMER ;}}; public final static Season SUMMER = new Season () {@ Override public Season nextQuarter () {return AUTUMN ;}}; public final static Season AUTUMN = new Season () {@ Override public Season nextQuarter () {return WINTER ;}}; public final static Sea Son WINTER = new Season () {@ Override public Season nextQuarter () {return SPRING ;}}; public abstract Season nextQuarter (); // print the enumerated value @ Override public String toString () {return this = WINTER? "Winter": (this = SPRING? "Spring": (this = SUMMER? "Summer": "Autumn") ;}} copy the code and run the result as follows: Winter 2. A basic enumeration class, which is defined in the class, as a member of the test class, an element in the class enumeration is equivalent to an object in the class, it automatically helps us to implement the toString method to print out the names of received references of enumeration values. Method name () to obtain the names of received references. Method ordinal () obtain the position of the enumerated value. The following table uses the static valueOf (String) method from 0) you can use the enumerated value name to obtain the enumerated value from the request parameter value obtained by the browser. In this way, you can program the static method values () of the enumerated value object () you can obtain all the enumerated values/Enumeration/src/yuki/core/enumeration/construction/SquareVertexTest in the Enumeration. java copy code package yuki. core. enumeration. constru Ction; public class SquareVertexTest {public static void main (String [] args) {SquareVertex vertex = SquareVertex. a; System. out. println (vertex); System. out. println (vertex. name (); System. out. println (vertex. ordinal (); System. out. println (SquareVertex. valueOf ("D"); System. out. println (SquareVertex. values (). length);}/*** four vertices of the square */public enum SquareVertex {A, B, C, D} copy the code and run the following: AA0D4 3. With Constructor Enumeration of methods is a class, so you should be able to define your own constructor. The constructor must be placed after the element list and add a semicolon after the element list. The constructor must be private, by default, no parameters are called to construct all enumeration values. When enumeration classes are used for the first time, all values are initialized. After enumeration elements, parentheses are added to specify the parameter list, you can call the corresponding constructor and add parentheses without content after the Enumeration element. The called method is also a constructor without parameters/enumeration/src/yuki/core/Enumeration/construction/DirectionTest. java copy code package yuki. core. enumeration. construction; public class DirectionTest {public static void main (String [] args) {@ SuppressWarnings ("unused") Direction direction = Direct Ion. w;} public enum Direction {E (1), S (), W, N; private Direction () {System. out. println ("construction method without Parameters");} private Direction (int direct) {System. out. println ("Direction (int direct)") ;}} copy the code and run the following result: Direction (int direct) no parameter constructor 4. Implement enumeration with abstract methods add an abstract method the return type is enumeration class itself add curly brackets after enumeration elements to implement this Abstraction method/Enumeration/src/yuki/core/enumeration/invalid action/ColorTest. java copy code package yuki. core. enumeration. billing action; pu Blic class ColorTest {public static void main (String [] args) {} public enum TrafficLamp {RED {@ Override public TrafficLamp nextLamp () {return GREEN ;}}, GREEN {@ Override public TrafficLamp nextLamp () {return YELLOW ;}}, YELLOW {@ Override public TrafficLamp nextLamp () {return RED ;}}; public abstract TrafficLamp nextLamp () ;}} copy the Code. In the bin directory, you can see that every element of the enumeration generates the class file D: \ Workspaces \ Eclipse \ Enumeratio. N \ bin \ yuki \ core \ enumeration \ specify action to specify a time for the lamp, add the construction parameter/Enumeration/src/yuki/core/enumeration/signing action/LampTest to the end of the Enumeration element. java copy code package yuki. core. enumeration. invalid action; public class LampTest {public static void main (String [] args) {} public enum TrafficLamp {RED (30) {@ Override public TrafficLamp nextLamp () {return GREEN ;}, GREEN (45) {@ Override public TrafficLamp nextLamp () {retur N YELLOW ;}, YELLOW (5) {@ Override public TrafficLamp nextLamp () {return RED ;}}; public abstract TrafficLamp nextLamp (); @ SuppressWarnings ("unused ") private int time; private TrafficLamp (int time) {this. time = time ;}} when copying code to create an anonymous subclass object of the parent class, you can specify the construction method/Enumeration/src/yuki/core/enumeration/aggregate action/ConstructorTest to call the parent class. java copy code package yuki. core. enumeration. define action; public class ConstructorT Est {public static void main (String [] args) {Supper supper = new Supper (1234) {@ Override public String toString () {return "toString method of subclass" ;}}; System. out. println (supper);} public static class Supper {public Supper () {System. out. println ("No parameter construction called");} public Supper (int I) {System. out. println ("parameter construction called") ;}} copy the code and run the following result: the toString method of the called subclass is constructed with parameters. If only one member is enumerated, can be used as a singleton mode. For more information, see [Zhang Xiaoxiang Java high-tech _ enumeration] v. Enumeration Functions and Demos 1. when Enumeration matches the enumerated values in switch-caseswitch, you only need to write the enumerated values without enumeration type./Enumeration/src/yuki/core/enumeration/switch_case/QuarkTest. java copy code package yuki. core. enumeration. switch_case; public class QuarkTest {public static void main (String [] args) {Quark quark = Quark. c; String name = null; switch (quark) {case U: name = "upper quark"; break; case D: name = "lower quark"; break; case C: name = ""; break; case S: name = "odd Quark "; break; case T: name =" "; break; case B: name =" "; break;} System. out. println (name);} private enum Quark {U, D, C, S, T, B;} copy the code and run the following result: 2. you can customize your own enumerated String so that you do not need to use public static final String variable_name = string_value;/Enumeration/src/yuki/core/enumeration/const_string/WebsiteTest. java copy code package yuki. core. enumeration. const_string; public class WebsiteTest {private enum Website {G OOGLE ("https://www.google.com.hk /? Gws_rd = ssl "), AMAZON (" http://www.amazon.cn/"); // URL private String address; // constructor private Website (String address) {this. address = address ;}// method for obtaining the address public String address () {return address ;}} public static void main (String [] args) {Website amazon = Website. AMAZON; System. out. println (amazon); System. out. println (amazon. address () ;}} copy the code and run the following result: AMAZONhttp: // www.amazon.cn/3. enumSet and EnumMap J When the Enum class is added in DK5.0, two tool classes EnumSet and EnumMap are added, both of which are included in the java. util package. /Enumeration/src/yuki/core/enumeration/enum_util/EnumSetTest. java copy code package yuki. core. enumeration. enum_util; import java. util. enumSet;/*** when the Enum class is added in JDK5.0, two tool classes EnumSet and EnumMap are added. * both classes are placed in java. util package. ** EnumSet is a high-performance Set interface implementation for enumeration types. * All enumeration objects installed in EnumSet must be of the same type. * In the EnumSet, it is implemented through bit-vector, that is, a long number. * EnumSet supports iteration in a certain range of all values of the enumeration type. ** @ Author yuki **/public class EnumSetTest {private enum WeekDay {Mon, Tue, Wed, Thu, Fri, Sat, Sun ;} public static void main (String [] args) {// EnumSet <WeekDay> weekDays = EnumSet. of (WeekDay. fri, WeekDay. tue); EnumSet <WeekDay> weekDays = EnumSet. range (WeekDay. tue, WeekDay. fri); for (WeekDay day: weekDays) {System. out. println (day) ;}} copy the code and run the following results: TueWedThuFri/Enumeration/src/yuki/core/enume Ration/enum_util/EnumMapTest. java copy code package yuki. core. enumeration. enum_util; import java. util. enumMap; import java. util. map;/*** similar to EnumSet, EnumMap is also a high-performance Map interface implementation. * It is used to manage the ing table using the enumeration type as the keys, and is implemented through arrays internally. * EnumMap combines rich and secure Map interfaces with quick access to arrays. * If You Want To Map an enumeration type to a value, you should use EnumMap. ** @ Author yuki **/public class EnumMapTest {// value private enum Divination {KAN, XUN, QIAN, DUI, LI, ZHENG, KUN, GEN} // natural value private enum Nature {SHUI, FENG, TIAN, ZE, HUO, LEI, DI, SHAN} public static void main (String [] args) {// Map the hexagrams to the natural values. Map <Divination, Nature> schema = new EnumMap <> (Divination. class); for (int I = 0; I <Divination. values (). length; ++ I) {schema. put (Divination. values () [I], Nature. values () [I]);} for (Map. entry <Divination, Nature> entry: schema. entrySet () {System. out. println (entry. getKey () + "\ t-> \ t" + entry. getValue () ;}} copy the code and run the following result: copy the code KAN> SHUIXUN> FENGQIAN> TIANDUI> ZELI> HUOZHENG> LEIKUN> DIGEN> SHAN

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.