LastStar007
LastStar007

Reputation: 765

Map with polymorphic generics

I have a method (let's call it doSomething) which takes in a Map<String,Object> and I want to pass in a Map<String,Foo> (Foo extends Object, of course). When I compile, it says that doSomething cannot be applied to the given types. Here is my code:

    public class FooMapChoo {

        private Map<String, Foo> map;

        public void doSomething(Map<String,Object>) {
        }

        public static void main(String...args) {
            doSomething(map);
        }

    }

Compiler output:

    method doSomething in class FooMapChoo cannot be applied to given types;
                    doSomething(map);
                    ^
      required: Map<String,Object>
      found: Map<String,Foo>

It seems to me that Foo should be polymorphically cast to Object. I've also tried casting map to Map<String,Object>, which just tells me "inconvertible types". What can I do to fix the polymorphism problem?

Upvotes: 0

Views: 797

Answers (1)

Antimony
Antimony

Reputation: 39451

You need to use wildcards

Map<String, ? extends Object>

Upvotes: 6

Related Questions