[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.
11/13/2020 10:37:52 AMChris Ng
5 AnswersNew Answer
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
I am still open for a detailed and practical answer. Any attempt will be appreciated. Thanks.
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
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.
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