• September 6, 2014
  • Generics
  • Comments Off on Unbounded wildcard in generics

Unbounded wildcard in generics

Unbounded wildcard:

Unbounded wildcard is used for list of unknown types using ‘?’(Type is not bounded).

Syntax: List<?>
Let us consider the below example:

public static void printListItems(List<object> list) {
    for (Object listItem : list)
        System.out.println(listItem);
}

In this example we want to print list items of any type but it can’t print List<Integer>, List<String> etc. because they are not subtypes of List<Object>. This problem can be solved using unbounded wildcard.

public static void printListItems(List<?> list) {
    for (Object listItem : list)
        System.out.println(listItem);
}

Unbounded wildcard example:


GenericsTest.java

import java.util.ArrayList;
import java.util.List;
 
/**
 * This class is used to show the 
 * ClassCastException at runtime test.
 * @author javawithease
 */
public class GenericsTest {
	//Only work for the list of object type.
	static void displayItems(List<Object> list){
	    for (Object listItem : list){
	        System.out.println(listItem);
	    }
	}
 
	//Work for the list of any type.
	static void displayListItems(List<?> list){
	    for (Object listItem : list){
	        System.out.println(listItem);
	    }
	}
 
	public static void main(String args[]){
		//Arraylist of Object type.	
		List<Object> list1 = new ArrayList<Object>();
		list1.add("Roxy");
		list1.add("Sandy");
		list1.add("Sunil");
 
		//Arraylist of string type.	
		List<String> list2 = new ArrayList<String>();
		list2.add("Amani");
		list2.add("Pabhjot");
		list2.add("Nidhi");	
 
		//Only accept Object type list.
		System.out.println("List of object " +
				"using displayItems method:");
		displayItems(list1);
 
		//Accept list of any type.
		System.out.println("List of object using " +
				"displayListItems method:");
		displayListItems(list1);
		System.out.println("List of strin using " +
				"displayListItems method:");
		displayListItems(list2);
 
	}
}

Output:

List of object using displayItems method:
Roxy
Sandy
Sunil
List of object using displayListItems method:
Roxy
Sandy
Sunil
List of strin using displayListItems method:
Amani
Pabhjot
Nidhi

Download this example.
 
Next Topic: Upper bounded wildcard.
Previous Topic: Wildcard in generics.

Related Topics:

How to build java project using ant in eclipse?
JAXB marshalling – convert java object to xml example.
How to create pdf file in java using iText jar?
Generics class example.
OGNL in struts 2.
Hibernate One-to-One Mapping using xml.
Send inline image in email using JavaMail API.
Quartz 2 JobListener example.

 


Comments are closed.