What does List<?>
mean, does it mean simply a list of objects of unspecified type?
Googling for the string <?>
returns nothing useful (:
What does List<?>
mean, does it mean simply a list of objects of unspecified type?
Googling for the string <?>
returns nothing useful (:
List<?>
stands forList<? extends Object>
so inCollection<E>
you will findcontainsAll(Collection<?> c)
which allows you to writeThe keyword you need to get more information is Wildcards
List
is an interface you can implement yourself and also implemented by some of the Java collections, likeVector
.You can provide compile-time typing information using the angled brackets. The most generic type would be
Object
, which would beList<Object>
. The<?>
you see is indicating a List of some subclass ofObject
or anObject
. This is like sayingList<? extends Object>
, orList<? extends Foo>
, where theList
contains objects of some subclass ofFoo
or objects ofFoo
itself.You can't instantiate a
List
; it's an interface, not an implementation.When you take an element out of a Collection, you must cast it to the type of element that is stored in the collection. Besides being inconvenient, this is unsafe. The compiler does not check that your cast is the same as the collection's type, so the cast can fail at run time.
Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of the collection.
chk dis pdf
As Tom said, the
?
, or unbounded wildcard, means that the type of the object is not specified. It could be unknown, could be meant for multiple possible values or might be just plain irrelevant. Your example,List<?>
, is pronounced "List of unknown." It's convenient because it's flexible, but there are also some pitfalls because you can't shove random objects in and pull them out of groups of unknown with total impunity.Resources:
Incidentally, your Google search failed because Google doesn't truck with special characters:
-Google help page
(EDIT: I must have been really tired when I wrote this last night. Cleaned up formatting/added a little info.)
To answer this question I need to explain Unbounded Wildcards and Bounded Wildcards.
The content of this post has been assembled from java documentation.
1. Unbounded Wildcards
2. Bounded Wildcards
Similarly, the syntax
? super T
, which is a bounded wildcard, denotes an unknown type that is a supertype of T. AArrayedHeap280<? super Integer>
, for example, includesArrayedHeap280<Integer>
,ArrayedHeap280<Number>
, andArrayedHeap280<Object>
. As you can see in the java documentation for Integer class, Integer is a subclass of Number that in turn is a subclass of Object.