Unbounded wildcards
The unbounded wildcard is represented as "?" and what we are saying is that there is a type parameter associated with it but we do not know the exact type.
File: "unbound2.java"
//: generics/UnboundedWildcards1.java
import java.util.*;
public class unbound2
{
public static void printList( List<Object> list )
{
for (Object elem : list)
System.out.println(elem + " ");
System.out.println() ;
}
public static void printList1(List list)
{
for (Object elem : list)
System.out.println(elem + " ");
System.out.println() ;
}
public static void printList2(List<?> list)
{
for (Object elem : list)
System.out.println(elem + " ");
System.out.println() ;
}
public static void main(String[] args)
{
List<Integer> li = Arrays.asList(1, 2, 3);
List<String> ls = Arrays.asList("one", "two", "three");
printList1(li);
printList2(li);
printList2(ls);
}
} ///:~
Output:
1
2
3
one
two
three
In the above we cannot convert "List<Integer" to "List<Object> list". However we can convert "List<Object>" to a "List<?>" or even a normal "List" .
Notice we cannot do:
public static void printList3(List<?> list)
{
list.add( "Something" ) ;
}
The "List<?>" states that the type is not known and if we don't know the type associated with the list then Java won't let us add an element to it.