我有一个Enum如下:
enum Mobile {
Samsung(400), Nokia(250),Motorola(325);
int price;
Mobile(int p) {
price = p;
}
int showPrice() {
return price;
}
}
Run Code Online (Sandbox Code Playgroud)
如何为Enum对象提供一个值,例如,如果输入为400,则输出应为Samsung Enum对象.
请建议.
在Mobile枚举本身中创建一个静态方法
public static Mobile getByPrice(int price) {
for (Mobile mobile : Mobile.values()) { // iterate all the values of enum
if (mobile.price==price) { // compare the price
return mobile; // return it
}
}
return null;
// either return null or throw IllegalArgumentException
//throw new IllegalArgumentException("No mobile found in this price:"+price);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
108 次 |
| 最近记录: |