Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

java - What's the purpose behind wildcards and how are they different from generics?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...