相关疑难解决方法(0)

混淆了嵌套泛型的集合

请帮助我理解原因add1()add4()报告错误以及为什么add2()add3()不报道错误.具体来说,如果编译器允许编译其中的每一个,请显示不良后果的示例.

class InnerTypeConfusion {
   interface Animal {}
   class Dog implements Animal {}
   class Room<T> {
      void add(T t) {}
   }

   void add1(Room<? extends Animal> room) {
      // Error: The method add(capture#1-of ? extends Animal) in the type 
      // Room<capture#1-of ? extends Animal> is not applicable for the 
      // arguments (Dog)
      room.add(new Dog());
   }

   void add2(Room<Animal> room) {
      room.add(new Dog());
   }

   class Cage<T> {}

   void add3(Room<Cage<? extends Animal>> room) {
      room.add(new Cage<Dog>());
   } …
Run Code Online (Sandbox Code Playgroud)

java generics collections covariance contravariance

2
推荐指数
1
解决办法
298
查看次数

标签 统计

collections ×1

contravariance ×1

covariance ×1

generics ×1

java ×1