2016-11-21 338 views
2

我正在使用java編寫基於文本的遊戲,並且希望爲地圖使用類似python的字典,因爲我想要將多個值鏈接到一個字典,所以HashMap對我來說並不真正起作用,例如,如何在java中創建一個字典,類似於python中的字典?

在Python中,你可以這樣定義字典:

room_x = { "name": "X", 

"description":"Random description", 

"exits": {linked to another dictionary}, 

"items": list_of_players_items} 

是類似的東西可能在Java中?

在此先感謝。

+0

任何原因,你沒有創建帶有字段類,如使用面嚮對象語言的一個好一點的面向對象編程? – Andreas

+0

在問一個新問題之前,請嘗試幾次Google搜索,特別是常見任務。 – TigerhawkT3

+1

@ TigerhawkT3只是FYI我並沒有特別要求HashMap解決方案,而是詢問如何從java中複製python中的字典函數(希望得到比HashMap更好的解決方案)。事實上,HashMap解決方案是最好的方法,但並不是它與你標記的問題一樣。 – MarkwinVI

回答

3

HashMap可以做的工作:

HashMap<String, String> hashMap = new HashMap<>(); //<key,value> both key and value are Strings 
hashMap.put("name", "X"); 
hashMap.put("description", "Random description"); 

要連結多個值。您需要更改的鍵值對類型作爲

HashMap<String,HashMap<String, String>> linkedMap = new HashMap<>(); // key is string and value is HashMap<String, String> 
HashMap<String,String> itemsMap = new HashMap<>(); 
itemsMap.put("item1", "this is first item"); 
itemsMap.put("item2", "this is second item"); 
linkedMap.put("items", itemsMap); 

上面的代碼是隻是一個簡單的例子,我寫,你需要聲明的實際類型數據的,它並沒有爲String
希望它有幫助。

0

HashMapHashtable就足夠了。兩者都有鍵值對,其中鍵是一個字符串,值可以是任何對象。因此,您可以將其定義爲HashMap<String, Object> map = new HashMap<String, Object>()

該值可以是任何值(即使HashMap不是Hashtable也是null)。

所以,你可以有另一個HashMap的價值,解決了「退出」:{鏈接到另一個字典}

而一個List作爲值,解決了「項目」:list_of_players_items

This給出了HashMap和Hashtable的區別。

示例代碼:

List players = // some List 
HashMap exits = // some Map 
HashMap<String, Object> room_x = new HashMap<String, Object>(); 
map.put("name",name_string); 
map.put("desc",desc_string); 
mp.put("exits",exits); 
map.put("items",players);