简体   繁体   English

Java继承和泛型,如何声明一个适用于“多种类型”继承的函数?

[英]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. 假设我有一个Map<k,v>类,它将键映射到值。

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? 那么, printMap函数签名应该是什么?

I tried with: void printMap(Map<Object, Horse>) But it doesn't work: 我试过: void printMap(Map<Object, Horse>)但它不起作用:

The method printMap(Map<Object,Horse>) in the type MainClass is not applicable for the arguments ( HyperMap<Pegasus,Horse> ) printMap(Map<Object,Horse>)类型中的方法printMap(Map<Object,Horse>)不适用于参数( HyperMap<Pegasus,Horse>

The method printMap(Map<Object,String>) in the type MainClass is not applicable for the arguments ( SuperMap<Unicorn,Horse> ) printMap(Map<Object,String>)类型中的方法printMap(Map<Object,String>)不适用于参数( SuperMap<Unicorn,Horse>

printMap(Map<?, Horse>)

或者,或者

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

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

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