Java枚举(或int常量)vs c enum

xir*_*irt 6 java enums coding-style

我正试图在C中做一些通常看起来像这样的事情:

typedef enum {
    HTTP  =80, 
    TELNET=23, 
    SMTP  =25, 
    SSH   =22, 
    GOPHER=70} TcpPort;
Run Code Online (Sandbox Code Playgroud)

方法1

以下是我在Java中使用的内容enum:

public static enum TcpPort{
    HTTP(80),
    TELNET(23),
    SMTP(25),
    SSH(22),
    GOPHER(70);

    private static final HashMap<Integer,TcpPort> portsByNumber;
    static{
        portsByNumber = new HashMap<Integer,TcpPort>();
        for(TcpPort port : TcpPort.values()){
            portsByNumber.put(port.getValue(),port);
        }
    }
    private final int value;
    TcpPort(int value){
        this.value = value;
    }
    public int getValue(){
        return value;
    }
    public static TcpPort getForValue(int value){
        return portsByNumber.get(value);
    }
}
Run Code Online (Sandbox Code Playgroud)

方法1 - 问题

我发现我不得不在不同的地方重复这种模式,但是想知道:有更好的方法吗?特别是因为:

  1. 这似乎令人费解,不那么优雅,而且
  2. 它还将编译时间改为运行时".

我使用此映射的原因之一是因为它在switch语句中看起来更好,例如:

switch(tcpPort){
    case HTTP:
        doHttpStuff();
        break;
    case TELNET:
        doTelnetStuff();
        break;
    ....
}
Run Code Online (Sandbox Code Playgroud)

我认为使用枚举更强的类型安全性也有好处.

方法2 我知道我能做到:

public static class TcpPort{
    public static final int HTTP   = 80;
    public static final int TELNET = 23;
    public static final int SMTP   = 25;
    public static final int SSH    = 22;
    public static final int GOPHER = 70;
}
Run Code Online (Sandbox Code Playgroud)

但我的感觉是,enums仍然更好.我的enum方法是否可行?还是有另一种方式?

And*_*niy 1

我的感觉是,在您的情况下,仅用于switch声明enum是多余的,最好简单地使用final static int常量。例如内存经济。

此外,Joshua Bloch 在他的Effective Java建议中使用enums 而不是int他的 中的常量Item 30: Use enums instead of int constants。但恕我直言,这是enum用于更复杂情况的正确方法,然后只是替换c #define构造。

更新:正如作者在对我的回答的评论中提到的那样,他想知道使用 if比一般的常量enum更好。int在这种情况下,这样的问题变得重复(参见Java: Enum vs. Int),我的答案将是:一般来说 enums 更好,为什么 - 看看 Joshua Bloch 的Item 30,正如我之前提到的。