2 回答
TA贡献1851条经验 获得超5个赞
您的枚举类型甚至无法编译,因为它缺少构造函数和私有字段。添加它时,很容易添加 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 只是用来以可读的方式打印数组。
TA贡献1864条经验 获得超6个赞
如果每个属性都有一个字段。
import java.util.Arrays;
import java.util.List;
class Coffee {
public static void main(String[] args) {
System.out.println(CoffeeTypes.COFFEE1.getAttributes());
}
public enum CoffeeTypes {
COFFEE1 ("AMERICANO", "LATTE", "CAPPUCCINO"),
COFFEE2 ("ESPRESSO", "RISTRETTO", "AMERICANO");
private String n1;
private String n2;
private String n3;
CoffeeTypes(String n1, String n2, String n3) {
this.n1 = n1;
this.n2 = n2;
this.n3 = n3;
}
public List<String> getAttributes() {
return Arrays.asList(n1, n2, n3);
}
}
}
输出
[AMERICANO, LATTE, CAPPUCCINO]
添加回答
举报