我有这样的代码:的Java:枚举/构造
public class Item{
String name, color;
int weight, volume, cost;
public Item(String name, int weight, int volume, int cost, String color){
this.name= name;
this.weight = weight;
this.volume = volume;
this.cost = cost;
this.color = color;
}
我用这个通过与数据csv文件加载创建项目的ArrayList。我有数组中的项目,如Apple,Pear,Noodles等。目前要查看项目,我必须调用itemList.get(2)。我希望能够调用itemList.APPLE或一些变体,所以我不必总是知道与该项目相关联的索引号。有没有办法做到这一点?这似乎是一个枚举技巧。
。
接着我有一个类,它是类似的,但我想创建与一个对象x:
项X =新项目(200,重量);输入:weight = 200,volume = 0,cost = 0,value = 0,base = 0,height = 0
x.toString()
从这个代码:
public class Item{
int weight, volume, cost, value,
base, height;
public Item(int x, String variable) {
//some code
}
在代码中我会通过将所有的变量等于0开始
,但后来我需要使用字符串值来选择哪些变量X增加。我将如何做到这一点?如果string.equals(“__”),但我简化了变量,那么我可以使用一个大的if if else else if语句将x添加到相应的变量中。其实大约有30个。我只需要做出一个很长的陈述或者是否有更好的方法?
如果您在运行时动态创建'enum',答案是否定的。 –
许多setter有什么问题? – Bohemian