Question

Can someone please explain to me difference between extends and super in java generics with wildcards?

I have read related posts and didn't get complete understanding. If you could explain me with real time example that would be great help for me.

what does PECS(producer you extend, consumes you use super) mean?

Was it helpful?

Solution

The type parameter <? extends T> means T or any subclass of T.

The type parameter <? super T> means T or any superclass of T.

For example:

  • Iterable<? extends T> supports any iterator whose next() method returns a T. This includes iterators that return a subclass of T.
  • Collection<? super T> supports any collection into which T's can be placed. This includes collections that can hold objects of any superclass of T.

In Effective Java, Joshua Bloch recommends the mnemonic PECS -- for "Producer-Extends, Consumer-Super".

"If a parameterized type represents a T producer, use <? extends T>; if it represents a T consumer, use <? super T>."

This is also known as the Get and Put Principle, from Java Generics by Maurice Naftalin and Philip Wadler.

"Use an extends wildcard when you only get values out of a structure, use a super wildcard when you only put values into a structure, and don't use a wildcard when you both get and put."

OTHER TIPS

If you have classes A, B and C where

A extends B

and

B extends C

Then

A and B match:

? extends B

and

B and C match:

? super B

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top