[JAVA Basics] enumeration, java Enumeration

Source: Internet
Author: User
Tags case statement

[JAVA Basics] enumeration, java Enumeration
Enumeration

Create a finite set as a new type, and the values in the set can be used as program components;

Enumeration Basic Features

The following code is a simple example of enumeration:

Returns the enum instance Array Using the values method.

Returns the order of each enum instance using the ordinal method, starting from 0.

Use the compareTo method to compare two enum instances

Use = to compare enum instances

Use the getDeclaringClass method to return the enum class to which the enum instance belongs.

Use the valueOf method to return the enum instance according to the specified name

package enumerated;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());            System.out.println(s.name());            System.out.println("----------------------");        }        // Produce an enum value from a string name:        for (String s : "HANGING CRAWLING GROUND".split(" ")) {            Shrubbery shrub = Enum.valueOf(Shrubbery.class, s);            System.out.println(shrub);        }    }}

Note that enum is inherited from java by default. lang. in the above Code, Shrubber is an enumeration class, GROUND, crawler, and HANGING are instances of this Enum class, because Shrubber has inherited from java. lang. enum class, so it cannot inherit other enum classes;

In addition, when using enumeration, you can consider using static import enumeration types, eliminating the need to use enumeration types to modify enumeration instances;

Add method to enum

Enum can basically be seen as a regular class, and you can add methods or even main methods to it;

The following code adds a constructor and a getDescription Method to the enumeration class. Note that when defining your own method, you need to add a semicolon after the last part of the enum instance sequence, you must first define the enum instance and then the method;

package enumerated;public enum OzWitch {    // Instances must be defined first, before methods:    WEST("Miss Gulch, aka the Wicked Witch of the West"),     NORTH("Glinda, the Good Witch of the North"),     EAST("Wicked Witch of the East, wearer of the Ruby Slippers, crushed by Dorothy's house"),     SOUTH("Good by inference, but missing");    private String description;    // Constructor must be package or private access:    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());    }}

Let's look at another example to overwrite the Enum class method. The code below overwrites the toString method and converts the first letter of the enumerated name into lowercase letters ,:

package enumerated;public enum SpaceShip {    SCOUT, CARGO, TRANSPORT, CRUISER, BATTLESHIP, MOTHERSHIP;    public String toString() {        String id = name();        String lower = id.substring(1).toLowerCase();        return id.charAt(0) + lower;    }    public static void main(String[] args) {        for (SpaceShip s : values()) {            System.out.println(s);        }    }}
Use enumeration in switch

The following code is used for enumeration in the switch statement. Note that in the case statement, you do not need to write the enumeration type before the enumeration instance. If you forcibly write (such as Signal. RED), the compiler reports an error;

package enumerated;// Define an enum type:enum Signal {    GREEN, YELLOW, RED,}public class TrafficLight {    Signal color = Signal.RED;    public void change() {        switch (color) {        // Note that you don't have to say Signal.RED        // in the case statement:        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();        }    }}
Values () method in Enumeration

We already know that the enumeration class inherits the java. lang. Enum class, but no values () method is found in the Enum source code. Where does the values () method come from?

The answer is that the values () method is a static method added by the compiler. If you are interested, you can use the reflection mechanism to view it. For the example above, you can compile the following code to view it:

Method[] methods = Signal.class.getMethods();

 

References: JAVA programming ideas-4

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.