在Java中扩展适当参数的参数

在Java中扩展适当参数的参数,java,Java,假设我有classAnimal和classBear,它们扩展了classAnimal。 现在在构造函数中,我有了带有Animal的参数: public class Forest { private List<Animal> animals; public Forest(List<Animal> list) { animals = list; } } 公共类林{ 私人动物名录; 公共森林(名单){ 动物=列表; } } 为什么我不能做那

假设我有class
Animal
和class
Bear
,它们扩展了class
Animal
。 现在在构造函数中,我有了带有
Animal
的参数:

public class Forest {

   private List<Animal> animals;

   public Forest(List<Animal> list) {
      animals = list;
   }
}
公共类林{
私人动物名录;
公共森林(名单){
动物=列表;
}
}
为什么我不能做那样的事

List<Bear> bears = new ArrayList<>();
new Forest(bears);
List bears=new ArrayList();
新森林(熊);
我认为熊在细节上是动物。
我只能通过将模板添加到
森林
来修复此问题吗

您可以使用通配符

  private List<? extends Animal> animals;

   public Forest(List<? extends Animal> list) {
      animals = list;
   }
后来

 List<Bear> bears = new ArrayList<>();
 Forest forest = new Forest(bears);

 forest.add(new Animal());

您也可以使用此方法

public static <C,T extends C> List<C> convert(List<T> list) {
        List<C> c = new ArrayList<>(list.size());
        c.addAll(list);
        return c;
}

new Forest(convert(bears));
公共静态列表转换(列表){
List c=新的ArrayList(List.size());
c、 addAll(列表);
返回c;
}
新森林(转换(熊));
很好的答案:)一个问题,在你初始化新森林(熊)的那一刻,你可以在这个森林里添加其他种类的动物吗??
 List<Bear> bears = new ArrayList<>();
 Forest forest = new Forest(bears);

 forest.add(new Animal());
 //same mix and bears lists from before
 Forest forest2 = new Forest(mix);
 forest2.addAll(bears);
public static <C,T extends C> List<C> convert(List<T> list) {
        List<C> c = new ArrayList<>(list.size());
        c.addAll(list);
        return c;
}

new Forest(convert(bears));