如何使用String数组填充枚举友好字符串

时间:2015-01-14 08:33:28

标签: java enums

我编码使用友好字符串名称填充我的枚举,例如游泳时间,徒步旅行时间......

public enum SeasonTypeEnum {
    summer("Swimming Time"),
    auturm("Hiking Time"),
    winter("Skiing Time"),
    spring("Planting Time");

    private String friendlyName;

    private SeasonTypeEnum(String friendlyName){
        this.friendlyName = friendlyName;
    }

    @Override
    public String toString(){
        return friendlyName;
    }
}

但是,我想将这些蜇在数组中存储并从中提取。我怎么能这样做?

3 个答案:

答案 0 :(得分:3)

最有可能enum是最佳解决方案,

我会像这样写一个数组的方式

static final String[] seasons = 
              "Swimming Time,Hiking Time,Skiing Time,Planting Time".split(",");

如果你想从枚举中提取,你可以这样做

static final SeasonTypeEnum[] VALUES = values();

public static String friendlyNameFor(int id) {
    return VALUES[id].friendlyName;
}

答案 1 :(得分:2)

您可以使用Enum.values()。

示例:

SeasonTypeEnum[] vals = SeasonTypeEnum.values();
String[] strs = new String[vals.length];
for (int i = 0; i < vals.length; i++) {
   strs[i] = vals[i].toString();
}

或者相反:

   public static SeasonTypeEnum getByStr(String val) {
      for (SeasonTypeEnum e : values()) {
         if (e.friendlyName.equals(val)) return e;
      }

      return null;
   }

答案 2 :(得分:1)

您可以将友好字符串存储在私有静态数组中,并通过添加索引作为输入字段与枚举条目相关联:

public enum SeasonTypeEnum {

    private static String seasons = new String[] {"Swimming Time", "Hiking Time", "Skiing Time", "Planting Time"};

    summer(0),
    auturm(1),
    winter(2),
    spring(3);

    private int index;

    private SeasonTypeEnum(int index) {
        this.index = index;
    }

    @Override
    public String toString() {
        return seasons[index];
    }
}