如何将枚举的一个变量中的所有元素加载到数组中?

我正在尝试使用另一个类中的方法将一个枚举变量的元素放入数组中(我希望我的解释是正确的,请查看代码)


我已经尝试过各种各样的事情,for 循环,有和没有构造函数。


public enum coffeetypes {

    COFFEE1 ("AMERICANO", "LATTE", "CAPPUCCINO"),

    COFFEE2 ("ESPRESSO", "RISTRETTO", "AMERICANO"), ;   

}

我想得到结果


"AMERICANO", "LATTE", "CAPPUCCINO" 

or "ESPRESSO", "RISTRETTO", "AMERICANO"

not "AMERICANO" "ESPRESSO"


慕运维8079593
浏览 152回答 2
2回答

江户川乱折腾

您的枚举类型甚至无法编译,因为它缺少构造函数和私有字段。添加它时,很容易添加 getElements() 方法,这样您就可以从枚举外部访问列表:import java.util.Arrays;public class Coffee {    public enum CoffeeTypes {        COFFEE1("AMERICANO", "LATTE", "CAPPUCCINO"),         COFFEE2("ESPRESSO", "RISTRETTO", "AMERICANO");        String[] elements;        private CoffeeTypes(String... elements)        {            this.elements=elements;        }        public String[] getElements()        {            return elements;        }    }    public static void main(String[] args) {        CoffeeTypes myinstance=CoffeeTypes.COFFEE1;        System.out.println(Arrays.asList(myinstance.getElements()));    }}Arrays.asList 只是用来以可读的方式打印数组。

慕尼黑的夜晚无繁华

如果每个属性都有一个字段。import java.util.Arrays;import java.util.List;class Coffee {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(CoffeeTypes.COFFEE1.getAttributes());&nbsp; &nbsp; }&nbsp; &nbsp; public enum CoffeeTypes {&nbsp; &nbsp; &nbsp; &nbsp; COFFEE1 ("AMERICANO", "LATTE", "CAPPUCCINO"),&nbsp; &nbsp; &nbsp; &nbsp; COFFEE2 ("ESPRESSO", "RISTRETTO", "AMERICANO");&nbsp; &nbsp; &nbsp; &nbsp; private String n1;&nbsp; &nbsp; &nbsp; &nbsp; private String n2;&nbsp; &nbsp; &nbsp; &nbsp; private String n3;&nbsp; &nbsp; &nbsp; &nbsp; CoffeeTypes(String n1, String n2, String n3) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.n1 = n1;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.n2 = n2;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.n3 = n3;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; public List<String> getAttributes() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return Arrays.asList(n1, n2, n3);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}输出[AMERICANO, LATTE, CAPPUCCINO]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java