Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

Vector<?> wilcardVector;

means

Vector<?> wilcardVector=null;

and calling wilcardVector.add(null); will lead to exception as wilcardVector=null

So, you ahve to use

wilcardVector = new Vector<String>();

wilcardVector = new Vector<String>(); should be sued when you are adding "only" Strings and nothing else.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top