I'm trying to do something that would normally look like this in C:
typedef enum {
HTTP =80,
TELNET=23,
SMTP =25,
SSH =22,
GOPHER=70} TcpPort;
Approach 1
Here is what I 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 that I am having to repeat this pattern in various places, but was wondering: is there a better way? particularly because:
One of the reasons I use this mapping, is because it looks better in switch statements, e.g.:
switch(tcpPort){
case HTTP:
doHttpStuff();
break;
case TELNET:
doTelnetStuff();
break;
....
}
I suppose there are also benefits of stronger type safety with enums.
Approach 2 I am aware I could 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 my feeling is that enum
s are still better. Is my enum
approach above the way to go? or is there another way?
My feeling is that in purposes only for switch
statement enum
is superfluous in your case, and it is better simply using final static int
constants. For instance of memory economy.
Also, Joshua Bloch in his Effective Java
recommends using enum
s instead of int
constants in his Item 30: Use enums instead of int constants
. But IMHO it is correct way of enum
using for more complicated cases then just replacing c
#define
construction.
UPDATE: as author mentioned in his comment to this my answer, he is wondering is use if enum
is better then int
constants in general. In this case such question becomes duplicate (see Java: Enum vs. Int), and my answer will: in general enum
s are better, and why - look at Joshua Bloch's Item 30
, as I mentioned before.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With