[英]Java: Enums / constructors
我有以下代码:
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,重量);
x.toString()......输出:重量= 200,体积= 0,成本= 0,值= 0,基数= 0,高度= 0
从此代码:
public class Item{
int weight, volume, cost, value,
base, height;
public Item(int x, String variable) {
//some code
}
在代码中,我将从将所有变量设置为0开始,但是然后我需要使用字符串值来选择要添加x的变量。 我该怎么做? 如果string.equals(“ __”),我可以使用if语句较大的if if else语句将x添加到各个变量中,但是我简化了变量; 实际上大约有30个。 我是否只需要声明很长的if语句,还是有更好的方法?
首先,根据您使用的列表抽象,可以指定将值放置在何处。 相反,如果您想随时检索特定对象,请查看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
当然,您需要在执行此操作之前覆盖equals()
和hashCode()
。 此外,将不允许您向映射输入重复的值。
接下来,第二步可以通过反射来完成,但是为什么不只使用常规的setter和getter?
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
将30个变量替换为Map,将每个名称映射到其值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.