2016-11-21 73 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);