Unbounded wildcard in generics

Unbounded wildcard:

Java generics unbounded wildcards : 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 w3spoint
 */
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.

 

Content Protection by DMCA.com
Please Share