2016-11-20 33 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來處理這些東西。