When following container will be useful
Vector<?> wilcardVector;
if only I can do with this is to create new container
wilcardVector = new Vector<String>();
or to add null
value
wilcardVector.add(null);
Trying to add some other types or pass with different generic method fails when compiling. So what is it for?
One valid use case for unbounded wildcard is to use it as a method parameter, when you only use those Vector's methods independent of type parameter, such as size()
, isEmpty()
, etc. :
something like :
void sampleMethod(Vector<?> vector) {
if (vector.isEmpty()) {
// your logic
}
}
and compiler will allow to pass any Vector
to sampleMethod
above.