First you should ask yourself the following question: Do you really need an int?
The purpose of enums is to have a collection of items (constants), that have a meaning in the code without relying on an external value (like an int). Enums in Java can be used as an argument on switch statments and they can safely be compared using "==" equality operator (among others).
Proposal 1 (no int needed) :
Often there is no need for an integer behind it, then simply use this:
private enum DownloadType{
AUDIO, VIDEO, AUDIO_AND_VIDEO
}
Usage:
DownloadType downloadType = MyObj.getDownloadType();
if (downloadType == DownloadType.AUDIO) {
//...
}
//or
switch (downloadType) {
case AUDIO: //...
break;
case VIDEO: //...
break;
case AUDIO_AND_VIDEO: //...
break;
}
Proposal 2 (int needed) :
Nevertheless, sometimes it may be useful to convert an enum to an int (for instance if an external API expects int values). In this case I would advise to mark the methods as conversion methods using the toXxx()
-Style. For printing override toString()
.
private enum DownloadType {
AUDIO(2), VIDEO(5), AUDIO_AND_VIDEO(11);
private final int code;
private DownloadType(int code) {
this.code = code;
}
public int toInt() {
return code;
}
public String toString() {
//only override toString, if the returned value has a meaning for the
//human viewing this value
return String.valueOf(code);
}
}
System.out.println(DownloadType.AUDIO.toInt()); //returns 2
System.out.println(DownloadType.AUDIO); //returns 2 via `toString/code`
System.out.println(DownloadType.AUDIO.ordinal()); //returns 0
System.out.println(DownloadType.AUDIO.name()); //returns AUDIO
System.out.println(DownloadType.VIDEO.toInt()); //returns 5
System.out.println(DownloadType.VIDEO.ordinal()); //returns 1
System.out.println(DownloadType.AUDIO_AND_VIDEO.toInt()); //returns 11
Summary
- Don't use an Integer together with an enum if you don't have to.
- Don't rely on using
ordinal()
for getting an integer of an enum, because this value may change, if you change the order (for example by inserting a value). If you are considering to use ordinal()
it might be better to use proposal 1.
- Normally don't use int constants instead of enums (like in the accepted answer), because you will loose type-safety.