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:14

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.

查看更多
ら面具成の殇う
3楼-- · 2018-12-31 10:14

So far, I have never needed to use enums. I have been reading about them since they were introduced in 1.5 or version tiger as it was called back in the day. They never really solved a 'problem' for me. For those who use it (and I see a lot of them do), am sure it definitely serves some purpose. Just my 2 quid.

查看更多
柔情千种
4楼-- · 2018-12-31 10:15

Apart from all said by others.. In an older project that I used to work for, a lot of communication between entities(independent applications) was using integers which represented a small set. It was useful to declare the set as enum with static methods to get enum object from value and viceversa. The code looked cleaner, switch case usability and easier writing to logs.

enum ProtocolType {
    TCP_IP (1, "Transmission Control Protocol"), 
    IP (2, "Internet Protocol"), 
    UDP (3, "User Datagram Protocol");

    public int code;
    public String name;

    private ProtocolType(int code, String name) {
        this.code = code;
        this.name = name;
    }

    public static ProtocolType fromInt(int code) {
    switch(code) {
    case 1:
        return TCP_IP;
    case 2:
        return IP;
    case 3:
        return UDP;
    }

    // we had some exception handling for this
    // as the contract for these was between 2 independent applications
    // liable to change between versions (mostly adding new stuff)
    // but keeping it simple here.
    return null;
    }
}

Create enum object from received values (e.g. 1,2) using ProtocolType.fromInt(2) Write to logs using myEnumObj.name

Hope this helps.

查看更多
笑指拈花
5楼-- · 2018-12-31 10:17

Enum? Why should it be used? I think it's more understood when you will use it. I have the same experience.

Say you have a create, delete, edit and read database operation.

Now if you create an enum as an operation:

public enum operation {
    create("1")
    delete("2")
    edit("3")
    read("4")

    // You may have is methods here
    public boolean isCreate() {
        return this.equals(create);
    }
    // More methods like the above can be written

}

Now, you may declare something like:

private operation currentOperation;

// And assign the value for it 
currentOperation = operation.create

So you can use it in many ways. It's always good to have enum for specific things as the database operation in the above example can be controlled by checking the currentOperation. Perhaps one can say this can be accomplished with variables and integer values too. But I believe Enum is a safer and a programmer's way.

Another thing: I think every programmer loves boolean, don't we? Because it can store only two values, two specific values. So Enum can be thought of as having the same type of facilities where a user will define how many and what type of value it will store, just in a slightly different way. :)

查看更多
春风洒进眼中
6楼-- · 2018-12-31 10:18

Enum inherits all the methods of Object class and abstract class Enum. So you can use it's methods for reflection, multithreading, serilization, comparable, etc. If you just declare a static constant instead of Enum, you can't. Besides that, the value of Enum can be passed to DAO layer as well.

Here's an example program to demonstrate.

public enum State {

    Start("1"),
    Wait("1"),
    Notify("2"),
    NotifyAll("3"),
    Run("4"),
    SystemInatilize("5"),
    VendorInatilize("6"),
    test,
    FrameworkInatilize("7");

    public static State getState(String value) {
        return State.Wait;
    }

    private String value;
    State test;

    private State(String value) {
        this.value = value;
    }

    private State() {
    }

    public String getValue() {
        return value;
    }

    public void setCurrentState(State currentState) {
        test = currentState;
    }

    public boolean isNotify() {
        return this.equals(Notify);
    }
}

public class EnumTest {

    State test;

    public void setCurrentState(State currentState) {
        test = currentState;
    }

    public State getCurrentState() {
        return test;
    }

    public static void main(String[] args) {
        System.out.println(State.test);
        System.out.println(State.FrameworkInatilize);
        EnumTest test=new EnumTest();
        test.setCurrentState(State.Notify);
        test. stateSwitch();
    }

    public void stateSwitch() {
        switch (getCurrentState()) {
        case Notify:
            System.out.println("Notify");
            System.out.println(test.isNotify());
            break;
        default:
            break;
        }
    }
}
查看更多
时光乱了年华
7楼-- · 2018-12-31 10:19

Besides the already mentioned use-cases, I often find enums useful for implementing the strategy pattern, following some basic OOP guidelines:

  1. Having the code where the data is (that is, within the enum itself -- or often within the enum constants, which may override methods).
  2. Implementing an interface (or more) in order to not bind the client code to the enum (which should only provide a set of default implementations).

The simplest example would be a set of Comparator implementations:

enum StringComparator implements Comparator<String> {
    NATURAL {
        @Override
        public int compare(String s1, String s2) {
            return s1.compareTo(s2);
        }
    },
    REVERSE {
        @Override
        public int compare(String s1, String s2) {
            return NATURAL.compare(s2, s1);
        }
    },
    LENGTH {
        @Override
        public int compare(String s1, String s2) {
            return new Integer(s1.length()).compareTo(s2.length());
        }
    };
}

This "pattern" can be used in far more complex scenarios, making extensive use of all the goodies that come with the enum: iterating over the instances, relying on their implicit order, retrieving an instance by its name, static methods providing the right instance for specific contexts etc. And still you have this all hidden behind the interface so your code will work with custom implementations without modification in case you want something that's not available among the "default options".

I've seen this successfully applied for modeling the concept of time granularity (daily, weekly, etc.) where all the logic was encapsulated in an enum (choosing the right granularity for a given time range, specific behavior bound to each granularity as constant methods etc.). And still, the Granularity as seen by the service layer was simply an interface.

查看更多
登录 后发表回答