I am trying 开发者_JAVA技巧to think of an elegant way to solve this problem in Java:
Given an int of 0-100 what is an elegant way to turn it into an enum where each of the enum's possible values correspond to a range of ints.
For example
enum grades{
A -> 90-95%
B -> 85-90%,
C -> 75-85%
...
etc
}
Can anybody think of a concise way to write a method that given an int returns an enum of grades or throws a IllegalArgumentException?
Write a static method, just like valueOf()
is already there, call it say inRange()
, return Grade
.
public enum Grade {
A(100, 90), B(89, 80), C(79, 70);
int uBound;
int lBound;
Grade(int uBound, int lBound){
...
}
public static Grade inRange(int percent){
...
}
}
Better initialize a static map
, percent as keys and Grade as values. I suggest you to use apache commons collection's MapUtils
in this case. Below is an example,
private static final Map<Integer, Grade> GRADE_MAP = UnmodifiableMap.decorate(
MapUtils.putAll(new HashMap<Integer, Grade>(), new Object[][]{
{0, F}, {1, F}, .....,
.....
.....
{100, A}
}));
then your method will look like below,
public static Grade inRange(int percent){
return GRADE_MAP.get(percent);
}
I'd make the boundaries an attribute of the enum, and implement a method
public boolean isInRange(int i)
in the enum, using the boundary and the boundary of the enum with the next lower ordinal number.
Finally implement a static method on the enum, that iterates through the instances to find the matching instance.
Ahead of time create an array with index 0..100 and assign each slot to the value you want it to correspond to.
Then in the actual loop just look the value up in the array.
精彩评论