如何从提供的值返回Enum对象

Anu*_*jee 1 java enums

我有一个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对象.

请建议.

Bra*_*raj 5

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)