Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Practical usage of wildcard generics in Java

I recently had an exam on Java, and there was a wide section about wildcard generics in Java. However, there is very little said about their usage in practice. When should we use them? Let's see a typical usage:

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

What the documentation says, that this collection does not allow to add any elements to the list. So basically wildcards can be used for making collections read-only. Is that their only usage? Is there any practical need for that? For the last four years I took part in a lot of programming projects in Java, but I haven't seen any project that would use extensively such a feature as wildcard.

So, from the practical point of view, are there any situations when wildcard generics are unavoidable and necessary?

like image 370
SPIRiT_1984 Avatar asked Mar 21 '13 06:03

SPIRiT_1984


1 Answers

So, from the practical point of view, are there any situations when wildcard generics are unavoidable and necessary?

I don't think they are 'unavoidable and necessary' because the Java compiler erases them anyway. However, when using them you get the benefit of a tighter type check during compile-time and you avoid type casting. Who wants to type cast anyway? :)

Guidelines for Wildcard Use

Type Erasure

like image 177
Adrian M Avatar answered Oct 06 '22 00:10

Adrian M