Java general problems

The following code compiles, but if I uncomment the comment line, it won't. I'm confused why HashMap does extend abstractmap and declares that the first line of the map compiles normally

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 like this:

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

public class Test {

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

Solution

The first code is not safe – imagine what you really wrote:

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

Now?

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

We should have a concurrenthashmap - but in fact we only have one HashMap

If we reduce the number of generics in progress, it's actually much simpler to explain... Your scenario is actually equivalent to (for example):

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

It looks OK until you think its effectiveness (in terms of compiler) is equivalent 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!

This is obviously inappropriate The compiler must handle both in the same way, so they both invalidate them

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>