2017-03-23 70 views
0
public Class Test{ 


    HashMap<String, HashMap<String, String>> GlobalMap = new HashMap(); 
    private String X; 



    public static void main(String[] args){ 
     Test t1 = new Test(); 
     t1.read(someTreeObject); 
     } 


@Override 
    public Void method1(someCtx) { 
     String A = "some value"; 
     String B = "some other value"; 

     Map Map1 = new HashMap(); 
     Map1.put(A,B); 

     System.out.println("Local Map : "+Map1.entrySet); 

     GlobalMap.put(X, (HashMap<String, String>)GlobalMap.get(X).putAll(Map1)); //<<<Compile time error details with the indicator pointing at Map1 within this line: error: incompatible types: void cannot be converted to HashMap<String,String> 

     // GlobalMap.put(X, (HashMap<String, String>)GlobalMap.get(X).put(new HashMap(A,B))); //<<<<<<<<<This is another approach, when tried gives a compile time error with the indicator pointing at A within this line: error: incompatible types: String cannot be converted to int 

     System.out.println("Global Map Details : \n"+GlobalMap.entrySet()+"\n");  

    } 
    return super.SomeMethod(someCtx); 

} 

Method1是一個重寫的方法,最初可用於抽象接口。 我知道我沒有想要發送給主要方法。參數化HashMaps:編譯時錯誤:不兼容類型

爲什麼putAll和put方法產生不同的錯誤信息? 我在這裏錯過了什麼?

我是編程和Java新手,真的想學習構建高級HashMaps。在我的經驗中早些時候使用泛型HashMap構造時,我沒有遇到類似於這個錯誤的任何東西。

+0

是的,[putAll](https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#putAll(java.util.Map))會返回void –

回答

0

您的錯誤與HashMapputAll方法返回nothing(void)的事實有關,因爲它只是將所有映射從地圖複製到另一個地圖。 查看更多here。 你可以在外面提取它,然後把地圖與複製的元素放在一起。

((HashMap<String, String>)GlobalMap.get(X)).putAll(Map1); 
GlobalMap.put(X, (HashMap<String, String>) Map1); 
0

方法HM2.putAll(HM1)將所有映射從HM1複製到HM2。它不會返回任何東西。所以,可能在你想演員之前做這個。

但是,不知道你在代碼中想要實現的是什麼 - 通過在不將任何東西放入全局映射中的情況下放置get(X),當它運行putAll()時會導致nullpointer。

+0

感謝您指出在那裏,我已經將null值與全局映射中的鍵字符串X相關聯。但是,我的想法是每次調用此方法時都會向Map1增量添加值。 – user8778

相關問題