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;

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

    public String getAbbreviation() {
        return abbreviation;
    }

    public String getColor() {
        return color;
    }
}

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

例如:

字符串品牌=“Y”;

我怎样才能得到相应的颜色(“commons.blue”)

4

4 回答 4

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")

于 2013-10-30T19:25:10.550 回答
1

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

于 2013-10-30T19:25:30.843 回答
0

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

于 2013-10-30T19:24:27.257 回答
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);
    }
}
于 2013-10-30T19:27:21.847 回答