简体   繁体   English

参数化的HashMaps:编译时错误:类型不兼容

[英]Parameterized HashMaps : compile time error: incompatible types

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 is an overridden method originally available for use from an Abstract Interface. Method1是一种重写的方法,最初可从Abstract接口使用。 I know there is nothing that I expect to send to the main method. 我知道没有期望发送给main方法的内容。

why are the putAll and put methods yielding different error messages? 为什么putAll和put方法产生不同的错误消息? What am I really missing here ? 我在这里真的想念什么?

I am new to programming and Java and really trying to learn building advanced HashMaps. 我是编程和Java的新手,我真的想学习构建高级HashMaps。 I did not encounter anything similar to this error when using the generic HashMap constructions earlier in my experience. 根据我的经验,在使用通用HashMap构造时,没有遇到与此错误类似的错误。

Your error is related to the fact that putAll method from HashMap returns nothing (void), because it is just copy all the mappings from a map to another. 您的错误与HashMap putAll方法不返回任何内容(无效)有关,因为它只是将所有映射从一个映射复制到另一个映射。 See more here . 在这里查看更多。 You can extract it outside and then put the map with copied elements. 您可以将其提取到外部,然后将带有复制元素的地图放到地图上。

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

The method HM2.putAll(HM1) copies all the mappings from HM1 to HM2. 方法HM2.putAll(HM1)将所有映射从HM1复制到HM2。 It does not returns anything. 它不返回任何内容。 So, possibly do this before you want to cast. 因此,可能要在投射之前执行此操作。

However, not sure what are you trying to achieve here in your code - by putting a get(X) without putting anything into global map, which would result in nullpointer when you run putAll() on it. 但是,不确定在代码中要实现的目标-通过放置get(X)而不将任何内容放入全局映射中,这将在对它运行putAll()时导致空指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM