2013-10-30 96 views
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」)

回答

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

+0

是否有另一種方式做到這一點避免這一招? –

+0

不,你必須循環元素 – alex2410

+0

如果我把這個方法放到我的枚舉中,我該如何訪問它? –

0

最簡單的方法是遍歷values(),直到你找到正確的枚舉,然後返回它的顏色。

1

調用它,你將不得不喲創建您的枚舉的方法是循環通過你的元素,直到它罰款。

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); 
    } 
} 
相關問題