why do we need the pure <?>
in Java? Does anything passed can only be used as Object ? So it's the same useful as any class casted to Object (only 9 methods could be available)
Thanks
I mean, if you have List< ? > list, you can only use items as Object. This means list.get(0) gives you Object and nothing more. Yes, also I can store to there anything, but is it useful for you? It's like you have a good an expensive thing and put it to a garbage bin. The only you can get from a trash bin is trash. As well you can put any good object of any class to List but get only Object from there with only 9 methods.
There are two scenarios where an unbounded wildcard is a useful approach:
If you are writing a method that can be implemented using functionality provided in the
Object
class.When the code is using methods in the generic class that don't depend on the type parameter.
For example,List.size
, orList.clear
. In fact,Class<?>
is so often used because most of the methods inClass<T>
don't depend onT
.
For example, see Collections.swap
method:
public static void swap(List<?> list, int i, int j) {
final List l = list;
l.set(i, l.set(j, l.get(i)));
}
Knowing the type does not aid in swapping two elements within a List
, so an unbounded wildcard is used. You pass in a List
- any List
- and the method swaps the indexed elements. There is no type parameter to worry about.
For more information, see: Unbounded Wildcards.