根据另一家酒店获取enum的财产

时间:2013-10-30 19:21:49

标签: java enums

如果我有这个枚举

public static enum Motorcycle {
    YAMAHA("Y", "commons.blue"), BMW("B", "commons.red"), HONDA("H", "commons.yellow"), KAWASAKI("K", "commons.green");

    private String abbreviation;
    private String color;

    SampleStatus(String abbreviation, String color) {
        this.abbreviation = abbreviation;
        this.color = color;
    }

    public String getAbbreviation() {
        return abbreviation;
    }

    public String getColor() {
        return color;
    }
}

如果我有缩写,我该如何获得颜色?

E.g:

String brand =“Y”;

如何获得相应的颜色(“commons.blue”)

4 个答案:

答案 0 :(得分:2)

主要方法:

  public static void main(String... s){
    for(Motorcycle m : Motorcycle.values()){
        if(m.getAbbreviation().equals("Y")){
            System.out.println(m.getColor());
            break;
        }
    }
  }

编辑使用此:

 public static String getColorByAbbreviation(String abbreviation){
    for(Motorcycle m : Motorcycle.values()){
        if(m.getAbbreviation().equals(abbreviation)){
            return m.getColor();
        }
    }
    return "";
}

您可以通过Motorcycle.getColorByAbbreviation("B")

来调用它

答案 1 :(得分:1)

你可以在你的枚举中创建一个循环遍历你的元素的方法,直到它被罚款。

答案 2 :(得分:0)

最简单的方法是迭代values(),直到找到正确的枚举,然后返回其颜色。

答案 3 :(得分:0)

像这样设置你的枚举:

public static enum Motorcycle {
      YAMAHA("Y", "commons.blue"), BMW("B", "commons.red"), HONDA("H", "commons.yellow"), KAWASAKI("K", "commons.green");

    private String abbreviation;
    private String color;

    private static Map<String, Motorcycle> motorcyclesByAbbr = new HashMap<String, Motorcycle>();

    static {
         for (Motorcycle m : Motorcycle.values()) {
             motorcyclesByAbbr.put(m.getAbbreviation(), m);
         }
    }
    SampleStatus(String abbreviation, String color) {
        this.abbreviation = abbreviation;
        this.color = color;
    }

    public String getAbbreviation() {
        return abbreviation;
    }

    public String getColor() {
        return color;
    }

    public static Motorcycle getByAbbreviation(String abbr) {
        return motorcyclesByAbbr.get(abbr);
    }
}