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) {
        System.out.println(e);
    }
}

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) {
         System.out.println(number);
     }
 } 

? extends Number should accept numbers only.

Useful Links :

https://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html

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.