Java enum (or int constants) vs c enum -


i'm trying in c:

typedef enum {     http  =80,      telnet=23,      smtp  =25,      ssh   =22,      gopher=70} tcpport; 

approach 1

here have in java, using 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);     } } 

approach 1 - problems

i find having repeat pattern in various places, wondering: there better way? particularly because:

  1. this seems convoluted , less elegant, ,
  2. it shifts compile time run time".

one of reasons use mapping, because looks better in switch statements, e.g.:

switch(tcpport){     case http:         dohttpstuff();         break;     case telnet:         dotelnetstuff();         break;     .... } 

i suppose there benefits of stronger type safety enums.

approach 2 aware do:

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; } 

but feeling enums still better. enum approach above way go? or there way?

my feeling in purposes switch statement enum superfluous in case, , better using final static int constants. instance of memory economy.

also, joshua bloch in effective java recommends using enums instead of int constants in item 30: use enums instead of int constants. imho correct way of enum using more complicated cases replacing c #define construction.

update: author mentioned in comment answer, wondering use if enum better int constants in general. in case such question becomes duplicate (see java: enum vs. int), , answer will: in general enums better, , why - @ joshua bloch's item 30, mentioned before.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -