View RSS Feed

Advanced Java

Unbounded Wildcards with Generics

Rate this Entry
by , 11-29-2011 at 11:09 PM (2627 Views)
When you as a programmer decide to use an unbounded wildcard <?>, it appears to mean anything. and so using an unbounded wildcard seems equivalent to using a raw type. There are time that the compiler is indifferent as to using raw type or <?>. If you use <?> it can be considered as a decoration. When you are using the raw type, the generic parameter can hold any type. In this example I show an important use of unbounded wildcards. If you are dealing with multiple generic parameters, itís best to allow one parameter to be any type if possible, while establishing a particular type for the other parameter:

Java Code:
import java.util.*;

public class WildcardExample { 
   static Map map1; 
   static Map<?,?> map2; 
   static Map<String,?> map3; 
   static void assign1(Map map) { map1 = map; } 
   static void assign2(Map<?,?> map) { map2 = map; } 
   static void assign3(Map<String,?> map) { map3 = map; } 

   public static void main(String[] args) {
      assign1(new HashMap()); 
      assign2(new HashMap()); 
      assign1(new HashMap<String,Integer>()); 
      assign2(new HashMap<String,Integer>()); 
      assign3(new HashMap<String,Integer>());
So using wildcards allows you to accept a wide range of parameterized types as arguments. The question is which trade-off is best for your needs depending on the context.

Submit "Unbounded Wildcards with Generics" to Facebook Submit "Unbounded Wildcards with Generics" to Digg Submit "Unbounded Wildcards with Generics" to Submit "Unbounded Wildcards with Generics" to StumbleUpon Submit "Unbounded Wildcards with Generics" to Google