如何从不同的枚举元素创建数组

时间:2014-03-18 01:16:48

标签: java enums

public enum CostData {
    IMPRESSIONS("Impressions", "Impressions"),
    CLICKS("Clicks", "Clicks"),
    COST("Expenditure", "Cost"),
    CONVERSION("Conversion", "Conversions");

    private String value1;
    private String value2;

    private CostData(String value1, String value2) {
        this.value1 = value1;
        this.value2 = value2;

    }

    public String getValue1() {
        return value1;
    }

    public String getValue2() {
        return value2;
    }
}

我需要创建一个包含ImpressionsClicksExpenditureConversion的数组,每个枚举元素中的第一个元素,另一个数组中包含第二个元素的数组枚举元素。有什么建议?

2 个答案:

答案 0 :(得分:1)

如果我理解你想要做的是:

List<String> firstArray = new ArrayList<String>();
List<String> secondArray = new ArrayList<String>();
for(CostData c : CostData.values()) {
    firstArray.add(c.getValue1());
    secondArray.add(c.getValue2());
}

答案 1 :(得分:0)

如果我做得对,你应该这样做。

    int length = CostData.values().length;
    String[] firstArray = new String[length];
    String[] secondArray = new String[length];
    int idx = 0;
    for(CostData cd: CostData.values()){
        firstArray[idx] = cd.getValue1();
        secondArray[idx++] = cd.getValue2();
    }