0

I'm trying to call a Java method with a HashMap as the parameter. The HashMap takes a String as it's key, and an Object as it's value. When I call that method, I send up a HashMap with a String as its key and an object that I created, Building, as the value. Since an object by default extends the Object class, is this not valid? Similar to this?:

List<Integer> a = new ArrayList<>();

Here is the code that I am running:

private void populateMap(HashMap<String, Object> map){
    /*Code is in here*/
}

public static void main(String[] args){
    HashMap<String, Building> buildings = new HashMap<>();
    populateMap(buildings);
}

But it's resulting in an error, saying that I can't send the buildings HashMap, as the parameter is expecting an Object as the value. How is this different than the List/ArrayList example I included above, and is there any way that I can make this work? I want to be able to call this method with multiple HashMaps, each of which has it's own unique object as the value, but I wanted to avoid creating multiple identical methods with the only difference being the method header.

Sal
  • 1,471
  • 2
  • 15
  • 36
  • 3
    `private void populateMap(HashMap map)` – Dawood ibn Kareem Mar 05 '19 at 20:15
  • 2
    `HashMap` would allow you to put an `Integer` instead of a `Building`, which would break type safety. You can do `HashMap` if you want to support this usage as well as more generic maps. – shmosel Mar 05 '19 at 20:19
  • Thank you very much, it's now working with ? instead of Object, but if Java supports polymorphism in instances such as the List/ArrayList example I mentioned, how come it doesn't apply to this situation, if Building extends Object automatically? Am I understanding the implicit extension incorrectly? – Sal Mar 05 '19 at 20:25
  • Yes, you are understanding it incorrectly. Read Jon Skeet's answer [to this question](https://stackoverflow.com/q/2745265) - he explains it very nicely. – Dawood ibn Kareem Mar 05 '19 at 20:50

0 Answers0