我想在我的課上有一個嵌套的hastable來設置成分的數量。請考慮以下情況。使用枚舉的JAVA嵌套哈希表
場景:
一個配方有幾種成分:
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是一個食譜類的枚舉。
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)
問: 採取這種scenarion考慮。我怎樣才能設置一個散列表內另一個作爲關鍵枚舉?
爲什麼你需要一個散列表來存儲單位和ammout的成分?這可能是無用的類中的簡單屬性...... –
'HashTable'是一個「舊」類,現在推薦使用'HashMap'來代替,當然如果你不需要同步的話。 –
@TimothyTruckle,我想我的食譜現有成分列表,我會得到重複的成分,因爲在一個食譜中,我可以使用1檸檬,在另一個有3個檸檬。我認爲一種成分可以有像千卡,脂質等營養。這就是爲什麼我認爲配料的數量取決於配方,這就是爲什麼我認爲這可能是食譜的一個屬性。 – ePascoal