2016-11-20 32 views
0

我想在我的课上有一个嵌套的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考虑。我怎样才能设置一个散列表内另一个作为关键枚举?

+1

为什么你需要一个散列表来存储单位和ammout的成分?这可能是无用的类中的简单属性...... –

+0

'HashTable'是一个“旧”类,现在推荐使用'HashMap'来代替,当然如果你不需要同步的话。 –

+0

@TimothyTruckle,我想我的食谱现有成分列表,我会得到重复的成分,因为在一个食谱中,我可以使用1柠檬,在另一个有3个柠檬。我认为一种成分可以有像千卡,脂质等营养。这就是为什么我认为配料的数量取决于配方,这就是为什么我认为这可能是食谱的一个属性。 – ePascoal

回答

0

嗯,我想这是一个公平的答案,它为我工作..

事实上,在这种情况下,我们可以考虑叫部分的第三类,它是一种可扩展的方法,因为它的优势在于添加方法或更多的属性,如果明天我们想要一个“复杂”的部分,但在我的情况下,这本词典似乎符合我的需要。所以一个嵌套的HashTable/HashMap应该像这样定义:

Ingredient lemon = new Ingredient("lemon"); 
    Ingredient powder = new Ingredient("powder"); 

    HashMap<Ingredient,HashMap<uom,Integer>> portion = new HashMap<Ingredient,HashMap<uom,Integer>>(); 

    portion.put(lemon,new HashMap<uom, Integer>(){{put(uom.unit,1);}}); 
    portion.put(powder,new HashMap<uom, Integer>(){{put(uom.cup,2);}}); 

    Recipe lemon_cake = new Recipe("lemon cake","bla bla",portion,"Mr Martin"); 
1

您需要使用put()方法上达等Hashtable的太多:

Map<Recipe.uom,Integer> mass new HashMap<>(); 
mass.put(uom.unit,1); 
ingredient.put(new Ingredient("Lemon"),mass); 
2

我打算在这个答案使用HashMap代替HashTable,因为前者是现在的标准方法。

你必须构建“嵌套” HashMap分开,使用put方法:

Map<Recipe.uom, Integer> amount = new HashMap<>(); 
amount.put(Recipe.uom.unit, 1); 
Ingredient lemon = new Ingredient("Lemon", amount); 

我跟蒂莫西同意,这是不是一个真正的好设计。我个人会创建另一个类/接口Amount来处理这些东西。