Skip to content

Wildcards in Java

Question mark (?) is called as wildcards used to declare unknown types in Java.

Let’s see some examples.

Writing a method that prints out all the elements in a collection.

void printCollection(Collection<?> c) {
    for (Object e : c) {

Writing a generic function that print all elements in a collection which should be of number type (Integer, Long, Float, Double)

Here Bounded wildcards comes in a rescue.

public static void printNumbers(Collection<? extends Number> numbers) {
     for (Number number : numbers) {

? extends Number should accept numbers only.

Useful Links :

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.