how can i reverse lookup the string value if given the int value for the given enum? so if i am given an int value of 0 it should return a value of "Freshman 1"I cant figure it out.
public enum YearsInSchool {
FRESHMAN1(0, "Freshman 1"),
FRESHMAN2(1, "Freshman 2"),
SOPHOMORE1(2, "Sophomore 1"),
SOPHOMORE2(3, "Sophomore 2"),
JUNIOR1(4, "Junior 1"),
JUNIOR2(5, "Junior 2"),
SENIOR1(6, "Senior 1"),
SENIOR2(7, "Senior 2"),
GRADUATE(8, "Graduate"),
FACULTY(9, "Faculty");
private int intVal;
private String strVal;开发者_运维知识库
YearsInSchool(int intValIn, String strValIn){
intVal = intValIn;
strVal = strValIn;
}
public int getIntVal() {
return intVal;
}
public String getStrVal() {
return strVal;
}
}
YearsInSchool.values()[0];
will get you the first enum value.
Also enum has a built in ordinal()
method that returns it's index in the set. It seems like you are just replicating this with your intVal
.
If you don't want to make it dependent on order of constants, you can use a lookup table initialized in static
block:
public enum YearsInSchool {
...
private static Map<Integer, YearsInSchool> intsToValues = new HashMap<Integer, YearsInSchool>();
static {
for (YearsInSchool y: values())
intsToValues.put(y.getIntValue(), y);
}
public static YearsInSchool getByInt(int y) {
return intsToStrings.get(y);
}
}
This should return FRESHMAN1
.
YearsInSchool yis = (YearsInSchool) YearsInSchool.class.getEnumConstants()[0];
if you what "Freshman 1", you should be able to do yis.getStrVal()
If you use Bala's answer you are locked in to keeping everything in sequence. I prefer to create a lookup map.
private static Map<Integer, YearsInSchool> intMap
= new HashMap<Integer, YearsInSchool>();
in your ctor add the line
intMap.put(intVal, this);
add the method
public static YearsInSchool getByInt(int n) {
return intMap.get(n); // error handling omitted here
}
Now you can add more enum values for situations you did not consider; you don't need them all in order. (For example, you could have enums for REDSHIRT_FRESHMAN
etc.)
Just use the code below and you can call the method getStrValIn on enum class
public enum YearsInSchool {
FRESHMAN1(0, "Freshman 1"), FRESHMAN2(1, "Freshman 2"), SOPHOMORE1(2,
"Sophomore 1"), SOPHOMORE2(3, "Sophomore 2"), JUNIOR1(4, "Junior 1"), JUNIOR2(
5, "Junior 2"), SENIOR1(6, "Senior 1"), SENIOR2(7, "Senior 2"), GRADUATE(
8, "Graduate"), FACULTY(9, "Faculty");
private int intVal;
private String strVal;
YearsInSchool(int intValIn, String strValIn) {
intVal = intValIn;
strVal = strValIn;
}
public static String getStrValIn(int intValIn){
YearsInSchool[] values = values();
for (YearsInSchool yearsInSchool : values) {
if(yearsInSchool.getIntVal() == intValIn){return yearsInSchool.getStrVal();}
}
return null;
}
public int getIntVal() {
return intVal;
}
public String getStrVal() {
return strVal;
}
}
This will solve your problem
精彩评论