r123454321
r123454321

Reputation: 3403

Map/HashMap Casting?

So I have a method, setContainerSummaryMap, which takes in a Map<String, Map<String, Integer>>.

I also have a HashMap<Long, HashMap<String, Integer>>, called contIdDestQuanMapSoFar, which I am going to convert into a HashMap<String, HashMap<String, Integer>> with a HashMap<Long, String>, named contIdToScanIdMap, that maps the keys to one another. This method is below:

public HashMap<String, HashMap<String, Integer>> convertContSummaryMap() {
    HashMap<String, HashMap<String, Integer>> toRet = new HashMap<String, HashMap<String, Integer>>();
    for (Entry<Long, HashMap<String, Integer>> entry : contIdDestQuanMapSoFar.entrySet()) {
        toRet.put(contIdToScanIdMap.get(entry.getKey()), entry.getValue());
    }
    return toRet;
}

The problem is, when I call the method setContainerSummaryMap(currentPlan.convertContSummaryMap()), I get an error, saying that it is not applicable for the arguments HashMap<String, HashMap<String, Integer>>. How would I modify the datatypes for this to work? Thanks.

Upvotes: 0

Views: 1321

Answers (2)

Michael Lang
Michael Lang

Reputation: 3992

You can redefine your setContainerSummaryMap method:

public void setContainerSummaryMap(Map<String, ? extends Map<String, Integer>> map)

or, as Louis already suggested change the return type of your convertContSummaryMap to match:

public HashMap<String, Map<String, Integer>> convertContSummaryMap()

Upvotes: 2

Louis Wasserman
Louis Wasserman

Reputation: 198023

To make this work, the type of toRet must be HashMap<String, Map<String, Integer>>. As @SLaks stated, a HashMap<String, Map> is not the same as a HashMap<String, HashMap>.

Of course, the Maps you'll actually put into it will still be HashMaps.

Upvotes: 1

Related Questions