Search This Blog

Java Generics - Wildcards

In generic code, the question mark (?), called the wildcard, represents an unknown type. The wildcard can be used in a variety of situations: as the type of a parameter, field, or local variable; sometimes as a return type (though it is better programming practice to be more specific).

The wildcard is never used as a type argument for a generic method invocation, a generic class instance creation, or a supertype.

1. Wildcard Arguments With An Unknown Type:

The syntax for declaring this type of wildcard arguments is,

GenericType<?>

The arguments which are declared like this can hold any type of objects. For example, Collection<?> or ArrayList<?> can hold any type of objects like String, Integer, Double etc.