【发布时间】:2016-11-20 16:57:43
【问题描述】:
我想在我的班级中有一个嵌套的 hastable 来设置成分的数量。请考虑以下情况。
场景:
一个食谱有几种成分:
public class Ingredient {
private static int id;
String name;
public Ingredient(String name) {
this.name = name;
}
}
public class Recipe {
public static enum uom{
ml,gr, unit, teaspoon, tablespoon,cup,coffeespoon
};
public String name;
public Hashtable<Ingredient,Hashtable<uom,Integer>> ingredients;
public String description;
public Recipe(String name, String description, Hashtable<Ingredient,Hashtable<uom,Integer>> ingredients) {
this.name = name;
this.description = description;
this.ingredients = ingredients;
}
public static void main (String [] args) {
Ingredient lemon = new Ingredient("lemon");
Hashtable<Ingredient,Hashtable<Recipe.uom,Integer>> ingredient = null;
ingredient.put(new Ingredient("Lemon"),new Hashtable(uom.unit,1));
Recipe LemonPie = new Recipe("Lemon pie","blabla",ingredients);
}
}
在这种情况下,我想在配方中包含每种成分的数量,我认为哈希表是最好的方法。但是我怎么能在另一个里面设置一个哈希表(像这样):
{new Ingredient("Lemon") : {"unit":1}}
其中unit是类Recipe的枚举。
Hashtable<Ingredient,Hashtable<Recipe.uom,Integer>> ingredient = null;
ingredient.put(new Ingredient("Lemon"),new Hashtable(uom.unit,1));
上面写着Hashtable (int,float) in Hashtable cannot be applied to (Recipe.uom,int)
问题: 考虑到这种情况。如何在另一个以枚举为键的哈希表中设置哈希表?
【问题讨论】:
-
为什么需要一个哈希表来存储成分的单位和数量?这可能是 ungredient 类中的简单属性...
-
HashTable是一个“旧”类,现在建议使用HashMap,当然如果您不需要同步。 -
@TimothyTruckle,我想要一份我食谱中现有成分的列表,因为我会得到重复的成分,因为在一个食谱中我可以使用 1 个柠檬,而在另一个食谱中可以使用 3 个柠檬。我认为一种成分可能具有千卡、脂质等营养成分。这就是为什么我认为成分的数量取决于配方,这就是为什么我认为这可能是配方的属性。
-
@MrMartin 然后我觉得你错过了一个抽象。您可能需要一个
Quantity类,其中包含成分、单位和数量作为成员。并且您的收据应该有这个数量的列表(而不是地图)。
标签: java hashtable enumeration