another java generic question

前端 未结 6 786
别跟我提以往
别跟我提以往 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:37

    Collection is the supertype for all kinds of collection. It is not a collection that can hold any type. At least that was my misunderstanding of the whole concept.

    We can use it where we don't care about the generic type, like in this example:

    public static void print(Collection aCollection) {
      for (Object o:aCollection) {
        System.out.println(o);
      }
    }
    

    If we had chosen the signature instead:

    public static void print(Collection aCollection)
    
    
    

    we would have limited ourselves to collections of type Collection - in other words, such a method wouldn't accept a Collection type value.

    So a Collection type is not a collection that can take any type. It only takes the unknown type. And as we don't know that type (its unknown ;) ), we can never add a value, because no type in java is a subclass of the unknown type.

    If we add bounds (like ), the type is still unknown.

    You're looking for a declaration of a map, whose values all implement the Able interface. The correct declaration is simply:

    Map map;
    

    Let's assume we have two types A and B that subclass Able and two additional maps

    Map aMap;
    Map bMap;
    

    and want a, method that returns any map whose values implement the Able interface: then we use the wildcard:

    public Map createAorBMap(boolean flag) {
     return flag ? aMap: bMap;
    }
    

    (again with the constraint, that we can't add new key/value pairs to the map that is returned by this method).

    提交回复
    热议问题