[英]How can I get an enum from an interface to a class that implements that interface?
I am trying to get an enum from this interface: 我试图从此接口获取一个枚举:
public interface PizzaInterface {
public enum Toppings {
pepperoni, sausage, mushrooms, onions, greenPeppers;
}
}
to this class: 到这个班级:
public class Pizza implements PizzaInterface{
private String[] toppings = new String[5];
}
and be able to store it in the array. 并能够将其存储在阵列中。
(edit): I want to put it in a ArrayList if that changes anything. (编辑):如果要进行任何更改,我想将其放入ArrayList中。
The first thing you need to understand is that Enum will be static inside that Interface. 您需要了解的第一件事是Enum在该接口内将是静态的。 And call to values()
method on any enum will return the array of enums instances. 在任何枚举上调用values()
方法将返回枚举实例的数组。 So if you can work with Enum array rather than String, you should be using that values()
call like the way pbabcdefp mentioned above. 因此,如果您可以使用Enum数组而不是String,则应该像上面提到的pbabcdefp那样使用values()
调用。 : :
PizzaInterface.Toppings[] toppings = PizzaInterface.Toppings.values();
But if you need String contents, I would like to suggest you to use ArrayList. 但是,如果您需要String内容,我建议您使用ArrayList。 There are usually more benefits using ArrayList then to Arrays. 使用ArrayList通常比使用Arrays有更多的好处。 In that case , If I were you, I would add one static method inside the Enum class to return the list of strings, which I would have used in the Pizza class. 在那种情况下,如果我是你,我将在Enum类内添加一个静态方法以返回字符串列表,该列表将在Pizza类中使用。 Sample code would be like : 示例代码如下:
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;
}
}
} }
and 和
public class Pizza implements PizzaInterface{
private static List<String> toppings = PizzaInterface.Toppings.getList();
//use the toppings list as you want
} }
Why do you want a String[]
? 为什么要String[]
? A Toppings[]
would be better. Toppings[]
会更好。 You can do this with 你可以这样做
PizzaInterface.Toppings[] toppings = PizzaInterface.Toppings.values();
If you want to store your values as Strings you can do this: 如果要将值存储为字符串,可以执行以下操作:
private String[] toppings = names();
public static String[] names() {
Toppings[] toppings = PizzaInterface.Toppings.values();
String[] names = new String[toppings.length];
for (int i = 0; i < toppings.length; i++) {
names[i] = toppings[i].name();
}
return names;
}
otherwise just call the .values() method from your enum and you will get a array of Toppings 否则只需从您的枚举中调用.values()方法,您将获得一个Toppings数组
PizzaInterface..Toppings.values();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.