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;
}

我用它来创建一个项目的ArrayList,方法是将数据加载到csv文件中。我在数组中有一些项目,如苹果、梨、面条等。目前要查看这些项目,我必须调用itemList.get(2)。我希望能够调用itemList。APPLE或一些变体,这样我就不必总是知道与项目相关联的索引号了。有办法做到这一点吗?这似乎是一个枚举技巧。

接下来,我有一个类似的类,但我想用创建一个对象x

项目x=新项目(200,重量);

x.到字符串()。。。。。。。。。。。。。。。输出:重量=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添加到哪个变量。我该如何做到这一点?我可以使用一个大的if,if-else,if-erse语句,如果字符串.equals("__"),则将x添加到相应的变量中,但我简化了变量;实际上大约有30个。我只需要做一个很长的if声明,或者有更好的方法吗?

用Map替换30个变量,将每个名称映射到其值。

首先,根据您使用的列表抽象,您可以指定将值放在哪里。如果您想在任何时候检索特定对象,请查看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

最新更新