+ 16

[SOLVED]: Practical Example of Bounded Wildcards

Can somebody give a detailed and practical explanation on when to use bounded wildcards in Java? Ideally the explanation should take into account of contravariance and covariance. Thanks.

13th Nov 2020, 10:37 AM
Chris Ng
Chris Ng - avatar
5 Answers
+ 7
Hi all, Here's my second attempt to address the problem. My practical example would be to return the sum of 1, 2 and PI with any levels of approximation for PI, without using any casting whatsoever. This should apply for any other arbitrary list of numbers. Usually when we find the sum of a list of integers, we use List<Integer>. However that is rather specific and restrictive, since the list can only accept Integer for its parameter and nothing else. We might want to be more inclusive and accept something more general. A naive attempt to generalize would be to use List<Number>. However that would wrong since List<Integer> is not a subtype of List<Number>. Since we are producing a sum, we need to use contravariance. The correct solution would be to use upper bounded wildcard (contravariance) which would be List<? extends Number> instead. Here's the code. https://code.sololearn.com/cQ6RxDNIs575/?ref=app
22nd Nov 2020, 9:10 AM
Chris Ng
Chris Ng - avatar
+ 9
I am still open for a detailed and practical answer. Any attempt will be appreciated. Thanks.
14th Nov 2020, 1:58 AM
Chris Ng
Chris Ng - avatar
+ 8
Hi Avinesh, Thank you for your prompt reply. To my limited understanding, I know that when we talk about bounded wildcards, we usually refer to the acronym "Producer extends, Consumer super", as used by Joshua Bloch in his book Effective Java. Producer - "source" Covariance (read-only) <? extends MyClass> Consumer - "sink" Contravariance: (write-only) <? super MyClass> I have looked through books and online posts regarding the topic, but I want to know how it is used in real production-ready code. Thanks, Chris
13th Nov 2020, 1:42 PM
Chris Ng
Chris Ng - avatar
+ 4
I lack good understanding of this topic but I would ask you to share your views and I would share the little I know and let us see if we could come to a conclusion. This is indeed a very good question. I'm asking you to do the above because I don't want this question to remain unanswered.
13th Nov 2020, 12:09 PM
Avinesh
Avinesh - avatar
+ 4
Even I have somewhat equal understanding of what you just posted in your last comment. I really doubt if this being frequently used in development. Just like you mentioned, "extends" is used for get operations and "super" for put operations. All I can do for now is leave you with a couple of links that might be helpful as I myself do not have anything much to share on this. https://stackoverflow.com/questions/16707340/when-to-use-wildcards-in-java-generics Java documentation https://docs.oracle.com/javase/tutorial/java/generics/wildcardGuidelines.html
13th Nov 2020, 1:59 PM
Avinesh
Avinesh - avatar