通配符背后的目的是什么?它们与泛型有什么不同? [英] What's the purpose behind wildcards and how are they different from generics?

查看:101
本文介绍了通配符背后的目的是什么?它们与泛型有什么不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直到前几天,在阅读我老师的Java书籍之后,我从来没有听说过野马车,但我仍然不确定它是什么用途,为什么需要使用它。



比方说,我有一个超类 Animal 和几个子类,比如 Dog Cat Parrot 等等...现在我需要一个动物列表,我的第一个想法是这样的:

 列表< Animal> listAnimals 

相反,我的同事推荐如下内容:

 列表< ;?延伸动物> listAnimals 

为什么要使用通配符而不是简单泛型?

假设我需要一个get / set方法,我应该使用前者还是后者?它们有什么不同?

解决方案

当你声明局部变量时,通配符没有什么意义,但它们是真的



想象一下你有一个方法:

  int countLegs(List<?extends Animal> animals)
{
int retVal = 0;
for(Animal cur:animals)
{
retVal + = cur.countLegs();
}

return retVal;



$ b $ p
$ b

使用此签名,您可以执行此操作:

 列表< Dog>狗= ...; 
countLegs(狗);

列表< Cat>猫= ...;
countLegs(猫);

列表< Animal>动物园= ...;
countLegs(zoo);

但是,如果您声明 countLegs 这:

  int countLegs(List< Animal>动物)

然后在前面的例子中,只有 countLegs(zoo)会被编译,因为只有那个调用具有正确的类型。


I'd never heard about wildcars until a few days ago and after reading my teacher's Java book, I'm still not sure about what's it for and why would I need to use it.

Let's say I have a super class Animal and few sub classes like Dog, Cat, Parrot, etc... Now I need to have a list of animals, my first thought would be something like:

List<Animal> listAnimals

Instead, my colleagues are recommending something like:

List<? extends Animal> listAnimals

Why should I use wildcards instead of simple generics?

Let's say I need to have a get/set method, should I use the former or the later? How are they so different?

解决方案

The wildcards do not make a lot of sense when you declare local variables, however they are really important when you declare a parameter for a method.

Imagine you have a method:

int countLegs ( List< ? extends Animal > animals )
{
   int retVal = 0;
   for ( Animal cur : animals )
   {
      retVal += cur.countLegs( );
   }

   return retVal;
}

With this signature you can do this:

List<Dog> dogs = ...;
countLegs( dogs );

List<Cat> cats = ...;
countLegs( cats );

List<Animal> zoo = ...;
countLegs( zoo );

If, however, you declare countLegs like this:

int countLegs ( List< Animal > animals )

Then in the previous example only countLegs( zoo ) would have compiled, because only that call has a correct type.

这篇关于通配符背后的目的是什么?它们与泛型有什么不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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