是否可以像下面这样进行枚举
enum {
10 poor
100 rich
1000 very_rich
}
Run Code Online (Sandbox Code Playgroud)
所以当我按输入值搜索时,请说101.它会返回"富"吗?如何在枚举中做到这一点?可举个例子吗?我不想用forloop循环整个枚举来获取string_value.可能?
创建enum
就像使用一个额外的成员变量(包含值10
,100
和1000
).然后在枚举getWealth
中创建一个静态方法,根据参数找到正确的枚举值money
:
static enum Wealth {
POOR(10), RICH(100), VERY_RICH(1000);
private final int money;
private Wealth(int money) {
this.money = money;
}
public static Wealth getWealth(int money) {
Wealth found = POOR;
for (Wealth w : values())
if (w.money <= money)
found = w;
return found;
}
}
public static void main(String[] args) {
System.out.println(Wealth.getWealth(101));
System.out.println(Wealth.getWealth(9));
System.out.println(Wealth.getWealth(10000));
}
Run Code Online (Sandbox Code Playgroud)
输出继电器:
RICH
POOR
VERY_RICH
Run Code Online (Sandbox Code Playgroud)
我在你的一条评论中看到你想要在没有循环的情况下做到这一点.这可以通过一些技巧完成.首先,在此解决方案(10,100,1000)中无法更改您的值,因为它使用money
参数给出的字符串的长度:
static enum Wealth {
POOR, RICH, VERY_RICH; // 10, 100, 1000
public static Wealth getWealth(int money) {
int len = Integer.toString(money).length();
int ordinal = Math.max(0, Math.min(len - 2, values().length - 1));
return values()[ordinal];
}
}
Run Code Online (Sandbox Code Playgroud)
使用enum
with值,正如其他人已经建议的那样.
然后,不是通过枚举值执行暴力迭代搜索,而是提供一个静态lookup(int)
方法,通过所有值的有序列表/数组执行二进制搜索.
要执行搜索,请将中间值或中间值作为"root"开始,并将我们要查找的值与之比较.
如果我们正在寻找的价值正是如此,那么我们就完成了.如果它小于那个,那么我们再次从中间开始搜索值的下半部分.如果更大,则将其与之后的值进行比较,看它是否在范围内.如果它仍然更大,则在上半部分搜索,依此类推.
编辑:请求的代码示例.
public enum Wealth {
BROKE(0),
DESTITUTE(10),
POOR(100),
MIDDLE_CLASS(10000),
RICH(100000),
MILLIONAIRE(1000000),
BILLIONAIRE(1000000000);
private final int value;
private Wealth(final int value) {
this.value = value;
}
public final int getValue() {
return value;
}
/**
* @param v
* the value we're looking for
* @return Wealth
*/
public static Wealth lookup(final int v) {
final Wealth[] a = Wealth.values();
int min = 0;
int max = a.length - 1;
int i;
do {
i = (min + max) / 2;
final int av = a[i].value;
if (v < av) {
max = i;
} else if (v > av) {
if (i + 1 < a.length && v < a[i + 1].value) {
break;
}
min = i + 1;
}
} while (v != a[i].value && min < max);
if (min == max) {
return a[max];
}
return a[i];
}
}
Run Code Online (Sandbox Code Playgroud)
几点说明:
这假设Wealth
已经订购了值.否则,快速排序(双关语!)就可以了.
这可能不是最有效的实现,只是一个快速而肮脏的实现,改编自维基百科上的伪代码.
如果你的数量少于十几个,那么线性搜索可能仍然比二分搜索更有效(并且代码肯定更加不言自明).二进制搜索只有在您拥有数十个或数百个值时才会真正得到回报,并且您可以执行数百万次查找.
鉴于你的原始价值,这是邪恶的,过早的优化.我只是想把它作为那些使用大量价值观的人的选择.