What are enums and why are they useful?

2018-12-31 09:52发布

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 to such solution.

I have never used enums and I have been programing in Java for more than couple a years now. And apparently they changed a lot. Now they even do full blown support of OOP within themselves.

Now why and what for should I use enum in day to day programming?

标签: java enums
23条回答
琉璃瓶的回忆
2楼-- · 2018-12-31 10:33

Enums enumerate a fixed set of values, in a self-documenting way.
They make your code more explicit, and also less error-prone.

Why not using String, or int, instead of Enum, for constants?

  1. The compiler won't allow typos, neither values out of the fixed set, as enums are types by themselves. Consequences:
    • You won't have to write a pre-condition (or a manual if) to assure your argument is in the valid range.
    • The type invariant comes for free.
  2. Enums can have behaviour, just as any other class.
  3. You would probably need a similar amount of memory to use Strings, anyway (this depends on the complexity of the Enum).

Moreover, each of the Enum's instances is a class, for which you can define its individual behaviour.

Plus, they assure thread safety upon creation of the instances (when the enum is loaded), which has seen great application in simplifying the Singleton Pattern.

This blog illustrates some of its applications, such as a State Machine for a parser.

查看更多
无色无味的生活
3楼-- · 2018-12-31 10:34

enum means enumeration i.e. mention (a number of things) one by one.

An enum is a data type that contains fixed set of constants.

OR

An enum is just like a class, with a fixed set of instances known at compile time.

For example:

public class EnumExample {
    interface SeasonInt {
        String seasonDuration();
    }

    private enum Season implements SeasonInt {
        // except the enum constants remaining code looks same as class
        // enum constants are implicitly public static final we have used all caps to specify them like Constants in Java
        WINTER(88, "DEC - FEB"), SPRING(92, "MAR - JUN"), SUMMER(91, "JUN - AUG"), FALL(90, "SEP - NOV");

        private int days;
        private String months;

        Season(int days, String months) { // note: constructor is by default private 
            this.days = days;
            this.months = months;
        }

        @Override
        public String seasonDuration() {
            return this+" -> "+this.days + "days,   " + this.months+" months";
        }

    }
    public static void main(String[] args) {
        System.out.println(Season.SPRING.seasonDuration());
        for (Season season : Season.values()){
            System.out.println(season.seasonDuration());
        }

    }
}

Advantages of enum:

  • enum improves type safety at compile-time checking to avoid errors at run-time.
  • enum can be easily used in switch
  • enum can be traversed
  • enum can have fields, constructors and methods
  • enum may implement many interfaces but cannot extend any class because it internally extends Enum class

for more

查看更多
查无此人
4楼-- · 2018-12-31 10:34

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);
    }
}
查看更多
残风、尘缘若梦
5楼-- · 2018-12-31 10:37

There are many answers here, just want to point two specific ones:

1) Using as constants in Switch-case statement. Switch case won't allow you to use String objects for case. Enums come in handy. More: http://www.javabeat.net/2009/02/how-to-use-enum-in-switch/

2) Implementing Singleton Design Pattern - Enum again, comes to rescue. Usage, here: What is the best approach for using an Enum as a singleton in Java?

查看更多
怪性笑人.
6楼-- · 2018-12-31 10:39

Now why and what for should I used enum in day to day programming?

You can use an Enum to represent a smallish fixed set of constants or an internal class mode while increasing readability. Also, Enums can enforce a certain rigidity when used in method parameters. They offer the interesting possibility of passing information to a constructor like in the Planets example on Oracle's site and, as you've discovered, also allow a simple way to create a singleton pattern.

ex: Locale.setDefault(Locale.US) reads better than Locale.setDefault(1) and enforces the use of the fixed set of values shown in an IDE when you add the . separator instead of all integers.

查看更多
登录 后发表回答