Recent Tutorials and Articles
    Unbounded wildcard Generics in Java
    Published on: 9th August 2013

    This tutorial explains the unbounded wildcard Generics in Java and also discusses a possible use case for same.

    This tutorial assumes that you have got a basic understanding of upper and lower bounded wildcard generics types. If this sounds new to you, you are advised to read this before continuing further.

    In either lower or upper bounded wildcards, we have got a bounded type. However in some cases, you might not want to limit the generic types and to be able to accept any generic type.

    Let's say we have got the following code that prints the elements of a collection.

    CollectionPrinter.java
    package com.sts.allprogrammingtutorials.generics;
    
    import java.util.Collection;
    
    /**
     * @author Sain Technology Solutions
     *
     */
    public class CollectionPrinter {
    	
    	public void printCollection(Collection objectsToPrint) {
    		
    		System.out.println("[");
    		for(Object object : objectsToPrint) {
    			System.out.println(object.getClass().getCanonicalName() + ": " + object);
    		}
    		System.out.println("]");
    	}
    	
    }
    
    

    Since we want to print all the collections, we can't use any of upper or lower bounded wildcard generics. We already know that replacing Collection with Collection<Object> wouldn't work as that wouldn't accept any other generic types.

    This is where we find unbounded wildcard generic types useful.

    Unbounded Wildcard Generics

    Unbounded wildcard generic type is super type of all the generic types and therefore can accept any generic types. Unbounded generic types are represented using ?.

    Here is how our Collection printing example would look using generics -

    CollectionPrinterGenerics.java
    package com.sts.allprogrammingtutorials.generics;
    
    import java.util.Collection;
    
    /**
     * @author Sain Technology Solutions
     *
     */
    public class CollectionPrinterGenerics {
    	
    	public void printCollection(Collection<?> objectsToPrint) {
    		
    		System.out.println("[");
    		for(Object object : objectsToPrint) {
    			System.out.println(object.getClass().getCanonicalName() + ": " + object);
    		}
    		System.out.println("]");
    	}
    	
    }
    
    

    One thing worth noting here is that you can't add any type of objects to it as type of unbounded generic type is unknown. For the same reason, following code will not compile -

    Collection<?> unboundedGenericTypes = new ArrayList<String>();
    unboundedGenericTypes.add("Could be any object"); //Compile time error
    
    

    Thank you for reading through the tutorial. In case of any feedback/questions/concerns, you can communicate same to us through your comments and we shall get back to you as soon as possible.

    Published on: 9th August 2013

    Comment Form is loading comments...