我正在尝试从此界面获取枚举:
public interface PizzaInterface {
public enum Toppings {
pepperoni, sausage, mushrooms, onions, greenPeppers;
}
}
对于这个类:
public class Pizza implements PizzaInterface{
private String[] toppings = new String[5];
}
并能够将其存储在数组中。
(编辑): 如果有任何改变,我想将它放入 ArrayList 中。
最佳答案
您需要了解的第一件事是 Enum 在该接口(interface)内将是静态的。对任何枚举调用 values()
方法将返回枚举实例数组。因此,如果您可以使用 Enum 数组而不是 String,则应该像上面提到的 pbabcdefp 那样使用 values()
调用。 :
PizzaInterface.Toppings[] toppings = PizzaInterface.Toppings.values();
但是如果你需要String内容,我建议你使用ArrayList。使用 ArrayList 通常比使用数组有更多的好处。在这种情况下,如果我是你,我会在 Enum 类中添加一个静态方法来返回字符串列表,我会在 Pizza 类中使用该方法。示例代码如下:
public interface PizzaInterface {
public enum Toppings {
pepperoni, sausage, mushrooms, onions, greenPeppers;
public static List<String> getList(){
List<String> toppings=new ArrayList<String>();
for (Toppings topping:Toppings.values() ){
toppings.add(topping.name());
}
return toppings;
}
}
}
和
public class Pizza implements PizzaInterface{
private static List<String> toppings = PizzaInterface.Toppings.getList();
//use the toppings list as you want
}
关于java - 如何从接口(interface)获取枚举到实现该接口(interface)的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29811799/