java - List<Map<String, String>> vs List<?扩展 map <字符串,字符串>>

标签 java generics inheritance polymorphism

有什么区别

List<Map<String, String>>

List<? extends Map<String, String>>

?

如果没有区别,使用有什么好处?扩展

最佳答案

不同之处在于,例如,一个

List<HashMap<String,String>>

是一个

List<? extends Map<String,String>>

但不是

List<Map<String,String>>

所以:

void withWilds( List<? extends Map<String,String>> foo ){}
void noWilds( List<Map<String,String>> foo ){}

void main( String[] args ){
    List<HashMap<String,String>> myMap;

    withWilds( myMap ); // Works
    noWilds( myMap ); // Compiler error
}

你会认为 HashMapList 应该是 MapList,但是有一个不这样做的充分理由:

假设你可以这样做:

List<HashMap<String,String>> hashMaps = new ArrayList<HashMap<String,String>>();

List<Map<String,String>> maps = hashMaps; // Won't compile,
                                          // but imagine that it could

Map<String,String> aMap = Collections.singletonMap("foo","bar"); // Not a HashMap

maps.add( aMap ); // Perfectly legal (adding a Map to a List of Maps)

// But maps and hashMaps are the same object, so this should be the same as

hashMaps.add( aMap ); // Should be illegal (aMap is not a HashMap)

这就是为什么 HashMapList 不应该是 MapList 的原因。

关于java - List<Map<String, String>> vs List<?扩展 map <字符串,字符串>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9810445/

相关文章:

java - edittext 声明为 final,settext 不工作

c# - Autofac:使用非泛型接口(interface)注册泛型类型

java - 对于 Selenium 2.49.0,获取 org.openqa.selenium.WebDriverException : this. getChromeWindowFromDocumentWindow(...) 在 FF 上的窗口最大化时未定义

java - 如何为 Traceroute C 文件创建 JNI 接口(interface)

c# - 向我的类(class)添加功能

c# 重载具有不同参数约束的泛型函数

swift 继承 : Super's Super

c# - 静态接口(interface)等效 C#

c++ - C++中模板参数的类继承

java - 如何对JTable中JComboBox的字符串进行排序?