2013-12-16 91 views
0

我有这样的代码:的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个。我只需要做出一个很长的陈述或者是否有更好的方法?

+1

如果您在运行时动态创建'enum',答案是否定的。 –

+0

许多setter有什么问题? – Bohemian

回答

0

首先,根据您使用的列表抽象,您可以指定要放置值的位置。相反,如果你想在任何时间以检索到特定的对象,寻找到一个替代Map

Map<String, Item> itemMap = new HashMap<>(); 
itemMap.put("apples", new Item("Apple", 1, 1, 1, "Red")); 
itemMap.get("apples"); // gives you the item you placed in as an Apple 

当然,你会希望override equals() and hashCode()在这之前。此外,您将不被允许输入重复值到映射。

接下来,第二个可以用反射来完成,但为什么不使用传统的setter和getters?

Item item = new Item(); // or whichever constructor you choose 
item.setWeight(200); // sets weight to 200 
System.out.println(item); // will print item as you wish 
0

与地图更换30个变量,映射每个名字的价值。