Saturday, October 18, 2014

Wild Card Paramters in Java

In this post I'm going to give you a small introduction about Wild card parameters used is java.

In java, Type parameters for generics have a limitation. Generic type parameters should match exactly for assignments. for example, If we use following statement in a java program, it will give a compilation error of incompatible types.

List<Number> intList = new ArrayList<Integer>();

If we slightly change the above statement to use wildcard parameter, it will compile without any errors.

List<?> wildCardList = new ArrayList<Integer>();

So, what does a wildcard mean? It's just like the wildcard, you use for substituting for a card in a card game. In java, you can use a wildcard parameter to indicate that it can match any type. With List<?>, you can mean that it is a List of any type. But when you want a type a indicating "any type", you may use the Object class, don't you? How about the statement, but using the Object type parameter?

List<Object> wildCardList = new ArrayList<Integer>();

No luck, you will get same compilation error you got when you used the first statement. In this case you are still trying to use subtyping for generic parameters. As you can see, List<Object> and List<?> are not same. In face List<?> is a super type of any List type. which means you can pass List<Integer>, or List<String>, or even List<Object> where List<?> is expected.

Thanks