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

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

问题描述

直到几天前我才听说过通配符,在阅读了我老师的 Java 书籍后,我仍然不确定它的用途以及为什么需要使用它.

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.

假设我有一个超类 Animal 和几个子类,如 DogCatParrot,等等...现在我需要有一个动物列表,我的第一个想法是:

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?

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

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.

假设你有一个方法:

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 );

但是,如果您像这样声明 countLegs:

If, however, you declare countLegs like this:

int countLegs ( List< Animal > animals )

那么在前面的例子中,只有 countLegs( zoo ) 会编译,因为只有那个调用有正确的类型.

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

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

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