Java Inheritance and generics, how to declare a function that applies to "multiple types" of inheritance?

I couldn't find a good question/title for what I want to do. I'm not very familiar with generics, so I have some issues understanding how they work.

Say I have a Map<k,v> class that maps keys to values.

class Map<K,V>{
    public V get(K key){
        //...
    }

    public void set(K key, V v){
        //...
    }
 }

Then, I create two subclasses:

class SuperMap<K,V> extends Map<K,V>{ /* ... */ }
class HyperMap<K,V> extends Map<K,V>{ /* ... */ }

What I want is to create a function that can take any map and print the string representation of each key and value. So I could just:

SuperMap<Unicorn, Horse> unicornsMap = ....;
HyperMap<Pegasus, Horse> pegasusMap = ....;

printMap(unicornsMap);
printMap(pegasusMap);

So, what should be the printMap function signature?

I tried with: void printMap(Map<Object, Horse>) But it doesn't work:

The method printMap(Map<Object,Horse>) in the type MainClass is not applicable for the arguments (HyperMap<Pegasus,Horse>)

The method printMap(Map<Object,String>) in the type MainClass is not applicable for the arguments (SuperMap<Unicorn,Horse>)

Upvotes: 3

Views: 155

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198281

printMap(Map<?, Horse>)

or, alternately

<K> printMap(Map<K, Horse>)

Upvotes: 5

Related Questions