What are enums and why are they useful?

后端 未结 27 1307
一整个雨季
一整个雨季 2020-11-22 07:06

Today I was browsing through some questions on this site and I found a mention of an enum being used in singleton pattern about purported thread safety benefits

相关标签:
27条回答
  • 2020-11-22 07:30

    What is an enum

    • enum is a keyword defined for Enumeration a new data type. Typesafe enumerations should be used liberally. In particular, they are a robust alternative to the simple String or int constants used in much older APIs to represent sets of related items.

    Why to use enum

    • enums are implicitly final subclasses of java.lang.Enum
    • if an enum is a member of a class, it's implicitly static
    • new can never be used with an enum, even within the enum type itself
    • name and valueOf simply use the text of the enum constants, while toString may be overridden to provide any content, if desired
    • for enum constants, equals and == amount to the same thing, and can be used interchangeably
    • enum constants are implicitly public static final

    Note

    • enums cannot extend any class.
    • An enum cannot be a superclass.
    • the order of appearance of enum constants is called their "natural order", and defines the order used by other items as well: compareTo, iteration order of values, EnumSet, EnumSet.range.
    • An enumeration can have constructors, static and instance blocks, variables, and methods but cannot have abstract methods.
    0 讨论(0)
  • 2020-11-22 07:31

    In my experience I have seen Enum usage sometimes cause systems to be very difficult to change. If you are using an Enum for a set of domain-specific values that change frequently, and it has a lot of other classes and components that depend on it, you might want to consider not using an Enum.

    For example, a trading system that uses an Enum for markets/exchanges. There are a lot of markets out there and it's almost certain that there will be a lot of sub-systems that need to access this list of markets. Every time you want a new market to be added to your system, or if you want to remove a market, it's possible that everything under the sun will have to be rebuilt and released.

    A better example would be something like a product category type. Let's say your software manages inventory for a department store. There are a lot of product categories, and many reasons why this list of categories could change. Managers may want to stock a new product line, get rid of other product lines, and possibly reorganize the categories from time to time. If you have to rebuild and redeploy all of your systems simply because users want to add a product category, then you've taken something that should be simple and fast (adding a category) and made it very difficult and slow.

    Bottom line, Enums are good if the data you are representing is very static over time and has a limited number of dependencies. But if the data changes a lot and has a lot of dependencies, then you need something dynamic that isn't checked at compile time (like a database table).

    0 讨论(0)
  • 2020-11-22 07:32

    Something none of the other answers have covered that make enums particularly powerful are the ability to have template methods. Methods can be part of the base enum and overridden by each type. And, with the behavior attached to the enum, it often eliminates the need for if-else constructs or switch statements as this blog post demonstrates - where enum.method() does what originally would be executed inside the conditional. The same example also shows the use of static imports with enums as well producing much cleaner DSL like code.

    Some other interesting qualities include the fact that enums provide implementation for equals(), toString() and hashCode() and implement Serializable and Comparable.

    For a complete rundown of all that enums have to offer I highly recommend Bruce Eckel's Thinking in Java 4th edition which devotes an entire chapter to the topic. Particularly illuminating are the examples involving a Rock, Paper, Scissors (i.e. RoShamBo) game as enums.

    0 讨论(0)
  • 2020-11-22 07:32

    From Java documents -

    You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.

    A common example is to replace a class with a set of private static final int constants (within reasonable number of constants) with an enum type. Basically if you think you know all possible values of "something" at compile time you can represent that as an enum type. Enums provide readability and flexibility over a class with constants.

    Few other advantages that I can think of enum types. They is always one instance of a particular enum class (hence the concept of using enums as singleton arrives). Another advantage is you can use enums as a type in switch-case statement. Also you can use toString() on the enum to print them as readable strings.

    0 讨论(0)
  • 2020-11-22 07:32

    Java lets you restrict variable to having one of only a few predefined values - in other words, one value from an enumerated list. Using enums can help to reduce bug's in your code. Here is an example of enums outside a class:

    enums coffeesize{BIG , HUGE , OVERWHELMING }; 
    //This semicolon is optional.
    

    This restricts coffeesize to having either: BIG , HUGE , or OVERWHELMING as a variable.

    0 讨论(0)
  • 2020-11-22 07:32

    What gave me the Ah-Ha moment was this realization: that Enum has a private constructor only accessible via the public enumeration:

    enum RGB {
        RED("Red"), GREEN("Green"), BLUE("Blue");
    
        public static final String PREFIX = "color ";
    
        public String getRGBString() {
            return PREFIX + color;
        }
    
        String color;
    
        RGB(String color) {
            this.color = color;
        }
    }
    
    public class HelloWorld {
        public static void main(String[] args) {
            String c = RGB.RED.getRGBString();
            System.out.print("Hello " + c);
        }
    }
    
    0 讨论(0)
提交回复
热议问题