java泛型和通配符 [英] java generic and wild card

查看:126
本文介绍了java泛型和通配符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java泛型中,我明白通配符的意思是什么,超级和扩展,但没有得到为什么不允许我添加任何东西,为什么允许我在层次结构中添加upto SomeType,但在上面没有

  class Animal {} 
class Cat extends Animal {}

以下方法可以取Animal或Animal的子目录,即Cat,但没有别的
,我不允许添加任何内容,如果尝试添加,编译器阻止我为什么?

  void addAminal(List< ;? extends Aminal> aList){
list .add(new Cat()); //编译器错误
aList.add(new Animal()); //编译器错误
}

现在下面的方法可以接受任何Animal或任何超级动物的类型,但没有动物的子类型,并且我可以将对象添加到Animal或更低级别,所以当我尝试添加Object时,编译器会抱怨为什么?

  void addAnimal(List< ;? super Animal> aList){
aList.add(new Animal()); //没有错误
aList.add(new Cat()); //没有错误
aList.add(new Object()); //编译器错误为什么?

感谢
Arya



  class Tabby extends Cat 

{}

然后您做了以下操作:

 列表与LT;虎斑> aList = new ArrayList< Tabby>(); 
addAnimal(aList);

这个列表不应该有一个Animal或者一个不是Tabby的Cat ,但如果编译器没有标记错误,那就是你将会得到的。



原因是hou've指定了 addAnimal 列出一些可以扩展动物的东西,但是这可能会造成严重的限制。然而,这会编译:

  void addAnimal(List< Animal> aList){
aList.add(new猫()); // OK
aList.add(new Animal()); // $
}

使用 super 也是可行的,因为任何 Cat Animal 的实例都是动物


In java generic I understood what are the meanign of wild card, super and extends, but didn't get why does not allow me to add anything, and why allows me to add upto SomeType in hierarchy, but not above in the hierarchy?

class Animal {}
class Cat extends Animal{}

following method can take list of Animal or sub of Animal i.e Cat, but nothing else and I am not allowed to add anything, if try to add, compiler stops me why ?

void addAminal(List<? extends Aminal> aList){
       aList.add(new Cat()); // compiler error
       aList.add(new Animal()); // compiler error
}

Now following method can take any list of Animal or any super type of Animal, but no sub type of Animal, and I can add objects upto Animal or lower in hierarchy, so when I try to add Object, compiler complains why ?

void addAnimal(List<? super Animal> aList){
     aList.add(new Animal()); // no error
     aList.add(new Cat());     // no error
     aList.add(new Object()); // compiler error why ?
}

Thanks Arya

解决方案

Suppose you defined a new class:

class Tabby extends Cat {}

And then you did the following:

List<Tabby> aList = new ArrayList<Tabby>();
addAnimal(aList);

There's no surprise that this list should not have an Animal or even a Cat that isn't a Tabby, yet if the compiler didn't flag the error, that's what you would have.

The reason is that hou've specified addAnimal to take a list of something that extends Animal, but that something could be highly restrictive. This, however, would compile:

void addAnimal(List<Animal> aList){
    aList.add(new Cat()); // OK
    aList.add(new Animal()); // OK
}

The use of super also would work, because an instance of either Cat or Animal is an instance of any superclass of Animal.

这篇关于java泛型和通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆