2013-12-19 142 views
0

這是我的HashMap:哈希映射在哈希表嘗試插入一些

protected HashMap<String, HashMap<String, Player>> prisonsPlayers = new HashMap<String, HashMap<String, Player>>(); 

我嘗試插入它的東西:

prisonsPlayers.put(player.getWorld(), (HashMap<player.getName(), player>)); 

Erorr我得到:

Multiple markers at this line 
    - Syntax error, insert ")" to complete 
    Expression 
    - Syntax error on token ")", invalid 
    Expression 

我知道我做錯了什麼,但是我嘗試了,我做了什麼,我不知道如何將該數據插入到我的散列表中。有人能幫助我嗎?

+1

不,泛型是編譯時間,而不是運行時間。您不能將方法返回的值用作類型參數。也請查看Java語法。實際上,取消關於泛型的所有知識,並從Java泛型教程開始。 –

回答

2

此行

prisonsPlayers.put(player.getWorld(), (HashMap<player.getName(), player>)); 

應該是這樣

Map<String, Player> map = new HashMap<String, Player>(); 
map.put(player.getName(),player); 
prisonsPlayers.put(player.getWorld(), map); 
+0

真的,我在代碼中使用了更多的hashmaps,像這樣你確定嗎?: \t protected HashMap freePlayers = new HashMap (); \t \t protected HashMap loggedPlayers = new HashMap (); (String,HashMap >)prisonsPlayers = new HashMap >(); – user3009924

0

語法錯誤(或者邏輯,太?)

prisonsPlayers.put(player.getWorld(), (HashMap<player.getName(), player>)); 

嘗試這樣做

prisonsPlayers.put(player.getWorld(), (new HashMap<String, Player>())); 
prisonsPlayers.get(player.getWorld()).put(player.getName(), player); 
+0

感謝您的回答,但您的代碼將我標記爲「put」並且說:鏈接所有本地重命名引用(不會在其他文件中更改引用 ) – user3009924

0

Prabhkaran是完全正確的,有答案將工作。

代碼

HashMap<player.getName(), player> 

是無效的,因爲你是供應對象爲HashMap的通用參數,並且他們應該是類定義。

例子:

// Construct a HashMap with can contain Strings as keys and values 
HashMap<String, String> mymap = new HashMap<String, String>(); 

// add Strings to my hashmap 
mymap.put("hello","world"); 

是確定的,但

// compilation failure! 
new HashMap<"Hello","World">(); 

不是。