another java generic question

前端 未结 6 791
别跟我提以往
别跟我提以往 2020-12-08 17:39

I have the following class:

interface Able{/* ... */}
class A implements Able{/* ... */}

and I have

Map

        
6条回答
  •  半阙折子戏
    2020-12-08 18:40

    A good way to understand the issue is to read what the wildcard means:

    Map as;
    

    "A map with keys of type String and values of one type that extends Able."

    The reason why add operations are not allowed is because they "open the door" to introduce different types in the collection, which would conflict with the typing system. e.g.

    class UnAble implements Able;
    Map unableMap = new HashMap();
    Map ableMap = unableMap;
    ableMap.put("wontwork",new A()); // type mismatch: insert an A-type into an Unable map 
    

    A correct use of the the wildcard construction would be:

    Result processAble(Map) { ... read records & do something ... } 
    
    Map ableMap = new HashMap;
    ableMap.put("willwork",new A());
    processAble(as);
    processAble(unableMap); // from the definition above
    

提交回复
热议问题