First you have to ask yourself the following question: do you really need an int?
The purpose of enumerations is to have a collection of elements (constants) that have a value in the code, without relying on an external value (for example, int). Enumerations in Java can be used as an argument for switch parameters, and they can be safely compared using the equality operator "==" (among others).
Proposal 1 (unnecessarily):
Often there is no need for a whole number, just use this:
private enum DownloadType{ AUDIO, VIDEO, AUDIO_AND_VIDEO }
Using:
DownloadType downloadType = MyObj.getDownloadType(); if (downloadType == DownloadType.AUDIO) { //... } //or switch (downloadType) { case AUDIO: //... break; case VIDEO: //... break; case AUDIO_AND_VIDEO: //... break; }
Proposal 2 (necessary):
However, it can sometimes be useful to convert enum to int (for example, if the external API expects an int value). In this case, I would advise marking methods as conversion methods using toXxx() -Style. To print, 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() {
Summary
- Do not use Integer with enum if it is not needed.
- Do not rely on using
ordinal() to get an integer enumeration, because this value can change if you change the order (for example, by inserting a value). If you plan on using ordinal() , it might be better to use sentence 1. - Usually do not use int constants instead of enumerations (as in the accepted answer), because you will lose type safety.
yonojoy Mar 12 '14 at 11:39 2014-03-12 11:39
source share