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 syntax for declaring a simple type of wildcard arguments with an unknown type,
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.
Java Generics simple Wildcards Example
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
/**
* Wildcard Arguments With An Unknown Type
* @author javaguides.net
*
*/
public class WildCardSimpleExample {
public static void printCollection(Collection<?> c) {
for (Object e : c) {
System.out.println(e);
}
}
public static void main(String[] args) {
Collection<String> collection = new ArrayList<>();
collection.add("ArrayList Collection");
printCollection(collection);
Collection<String> collection2 = new LinkedList<>();
collection2.add("LinkedList Collection");
printCollection(collection2);
Collection<String> collection3 = new HashSet<>();
collection3.add("HashSet Collection");
printCollection(collection3);
}
}
Output:
ArrayList Collection
LinkedList Collection
HashSet Collection
Related Java Generics Examples
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course