I have a couple of suggestions. Feel free to discard if they are not right for you.
Since you say you need the ordinal number of the enum, you may go the other way:
if (ApplicationStatus.values()[Integer.parseInt(statusMasterId)] == ApplicationStatus.PendingVerification) {
// do your stuff
}
Be aware that as in the question Integer.parseInt(statusMasterId)
may throw a NumberFormatException
.
Another suggestion, the compare method from Jay Smith’s answer may be taken a step further to accept a string argument:
public enum ApplicationStatus {
Initiated(1), PendingVerification(2), NotEligible(3), Approved(4),
SoftDenial(5), Deferred(6), Saved(7), Cancelled(8),
Approved_NoSSN(9),PendingVerification_NoSSN(10),
Approved_Archeived(11);
private final int value;
// redundant representation of ordinal() as a string for comparison to other strings
private final String ordinalAsString;
private ApplicationStatus(int value) {
this.value = value;
ordinalAsString = String.valueOf(ordinal());
}
public int getStatusMasterId() {
return value;
}
public boolean compare(String stringValue) {
return this.ordinalAsString.equals(stringValue);
}
}
There is no risk of a NumberFormatException
, but you may consider the risk there is even worse: This will not recognize for example "+2"
or "02"
as representing the number 2. Whether you want to store the string value permanently in the enum object is questionable; if you are serious about wanting the comparison to be efficient, you do want to. Jay Smith’s code is using the value
, I have changed it to using ordinal()
.
Here’s the test!
String statusMasterId = "2";
if (ApplicationStatus.values()[Integer.parseInt(statusMasterId)] == ApplicationStatus.NotEligible) {
System.out.println("Not eligible");
}
if (ApplicationStatus.NotEligible.compare(statusMasterId)) {
System.out.println("Still not eligible using the compare() method");
}
This prints
Not eligible
Still not eligible using the compare() method
This is because ordinals start from 0, so NotEligible
, with a value of 3, has ordinal 2, it’s not the same thing.