Practical use of wildcard generics in Java

I recently had a Java exam, and the section on generic wildcards has been expanded in Java. However, very little is said about their use in practice. When should we use them? Consider a typical use:

void check(Collection<? extends Animal> list) { // Do something } 

The documentation says that this collection does not allow you to add any items to the list. Thus, mainly templates can be used to create read-only collections. Is this their only use? Is there any practical need? Over the past four years, I have been involved in many Java programming projects, but I have not seen a single project that makes wide use of such a function as a wildcard.

So, from a practical point of view, are there situations where universal subsets are inevitable and necessary?

+6
source share
3 answers

So, from a practical point of view, are there situations where wildcard generics are inevitable and necessary?

I do not think that they are "inevitable and necessary" because the Java compiler erases them anyway. However, when using them, you get the advantage of checking for a more rigid type at compile time and avoiding type casting. Who wants to type a letter anyway? :)

Wildcard Recommendations

Type Erasure

+3
source
 void check(Collection<? extends Animal> list) { list.add(new Animal()); // compile time error list.add(new Dog()); // compile time error. Dog is subclass of Animal class. } 

Java is developing such generics because it prohibits programmar to encode everything they want, otherwise, if it is allowed, and then they will find a mess in the runtime.

Someday in programming, you will get a script in which your check method does not want to add an item to the list, but wants to read that item.

You can add only null values.

+1
source

In short, what you say is wrong.

This has nothing to do with "creating read-only collections."

We can still add items to the input list because Collection declared the add(E) method.

The wildcard is straight forward, I think: you really want to limit the type of input, because your logic is only reasonable for a specific type.

For your example, your check may use some Animal method

 void check(Collection<? extends Animal> list) { // Do something for (Animal a : list) { a.checkAge(); // checkAge() is method of Animal } } 

Without ? extends Animal ? extends Animal The above code will not work, since the incoming list can be a collection of everything (not Animal).

Therefore, we want to make sure that the incoming collection is Collection or Collection, etc., so that our code really makes sense when we extract items from the list and treat the item as Animal.

0
source

All Articles