Java:应用于映射泛型类型的多态性

Java:应用于映射泛型类型的多态性,java,generics,polymorphism,Java,Generics,Polymorphism,我希望有一个函数(例如)在两种情况下都输出贴图的所有值: Map<String, String> map1 = new HashMap<String, String>(); Map<String, Integer> map2 = new HashMap<String, Integer>(); output(map1, "1234"); output(map2, "4321"); Map map1=newhashmap(); Map map2=新的

我希望有一个函数(例如)在两种情况下都输出贴图的所有值:

Map<String, String> map1 = new HashMap<String, String>();
Map<String, Integer> map2 = new HashMap<String, Integer>();
output(map1, "1234");
output(map2, "4321");
Map map1=newhashmap();
Map map2=新的HashMap();
输出(map1,“1234”);
输出(map2,“4321”);
但以下几点似乎不起作用:

public void output(Map<String, Object> map, String key) {
    System.out.println(map.get(key).toString()); 
}
公共无效输出(映射映射,字符串键){
System.out.println(map.get(key.toString());
}
对象类型的
字符串
整数

映射
不扩展
映射
,就像
列表
不扩展
列表一样。您可以将值类型设置为
通配符:

public void output(Map<String, ?> map, String key) {  // map where the value is of any type
    // we can call toString because value is definitely an Object
    System.out.println(map.get(key).toString());
}
public void输出(映射映射,字符串键){//Map,其中值为任何类型
//我们可以调用toString,因为value肯定是一个对象
System.out.println(map.get(key.toString());
}

您正在寻找的是Java中在
集合上引入多态性的尝试,它被称为。更具体到您的用例,将符合要求

@manouti在回答中使用了一个无界通配符(请参阅通配符链接中的详细信息),但您可以使用比这更具体的东西:一个上界通配符

例如,
Map
其中
Object
通常是最具体但仍然常见的类,所有使用的类都必须从中派生。例如,如果所有映射中的值都有一个公共父类(或“超级”)
YourParentClass
,那么在我的示例中,您可以用该类名替换
Object

请参阅