![](/img/trans.png)
[英]How can I get the proper enum that implements a particular interface in Java?
[英]How can I get an enum from an interface to a class that implements that interface?
我試圖從此接口獲取一個枚舉:
public interface PizzaInterface {
public enum Toppings {
pepperoni, sausage, mushrooms, onions, greenPeppers;
}
}
到這個班級:
public class Pizza implements PizzaInterface{
private String[] toppings = new String[5];
}
並能夠將其存儲在陣列中。
(編輯):如果要進行任何更改,我想將其放入ArrayList中。
您需要了解的第一件事是Enum在該接口內將是靜態的。 在任何枚舉上調用values()
方法將返回枚舉實例的數組。 因此,如果您可以使用Enum數組而不是String,則應該像上面提到的pbabcdefp那樣使用values()
調用。 :
PizzaInterface.Toppings[] toppings = PizzaInterface.Toppings.values();
但是,如果您需要String內容,我建議您使用ArrayList。 使用ArrayList通常比使用Arrays有更多的好處。 在那種情況下,如果我是你,我將在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
}
為什么要String[]
? Toppings[]
會更好。 你可以這樣做
PizzaInterface.Toppings[] toppings = PizzaInterface.Toppings.values();
如果要將值存儲為字符串,可以執行以下操作:
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;
}
否則只需從您的枚舉中調用.values()方法,您將獲得一個Toppings數組
PizzaInterface..Toppings.values();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.