Java通用问题 [英] Java Generic Question

查看:87
本文介绍了Java通用问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码编译,但如果我取消注释的评论线,它不,我很困惑为什么。 HashMap扩展了AbstractMap,并且第一行声明map的地方编译得很好。

The following code compiles but if I uncomment the commented line, it does not and I am confused why. HashMap does extend AbstractMap and the first line where map is declared compiles fine.

import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;

public class Test {

    public static void main(String args[]) {
        Map<String, ? extends AbstractMap<String, String>> map = new HashMap<String, HashMap<String, String>>();
        //map.put("one", new HashMap<String, String>());
    }
}

而且,我知道正确的方式是这个:

And, I know the "right way" is this:

import java.util.HashMap;
import java.util.Map;

public class Test {

    public static void main(String args[]) {
        Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();
        map.put("one", new HashMap<String, String>());
    }
}


推荐答案

第一个代码是不安全的 - 想象你实际写了:

The first code is unsafe - imagine you're actually written:

HashMap<String, ConcurrentHashMap<String, String>> strongMap = 
    new HashMap<String, ConcurrentHashMap<String, String>>();
Map<String, ? extends AbstractMap<String, String>> map = strongMap;

现在:

Now:

map.put("one", new HashMap<String, String>());
ConcurrentHashMap<String, String> x = strongMap.get("one");

我们应 具有 ConcurrentHashMap - 但实际上我们只有一个 HashMap

We should have a ConcurrentHashMap - but in reality we've only got a HashMap.

这实际上简单得多以解释是否我们减少了仿制药的使用量......您的情况真的等于(说):

This is actually a lot simpler to explain if we reduce the amount of generics going on... your scenario is really equivalent to (say):

List<? extends Fruit> list = new List<Apple>();
list.add(new Apple());

这看起来不错,直到你认为它在效度上是相等的(只要编译器

which looks okay, until you consider that it's equivalent in validity (as far as the compiler is concerned) to:

List<Apple> apples = new ArrayList<Apple>();
List<? extends Fruit> list = apples;
list.add(new Orange());
Apple apple = list.get(0); // Should be okay... but element 0 is an Orange!

显然不是好。编译器必须以相同的方式处理这两者,因此它们都是无效的。

which is obviously not okay. The compiler has to treat the two in the same way, so it makes both of them invalid.

这篇关于Java通用问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆